首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >GridBagLayout帮助

GridBagLayout帮助
EN

Stack Overflow用户
提问于 2012-10-20 19:24:25
回答 1查看 352关注 0票数 0

我尝试了所有的组合,看了所有的文档,但我不知道如何使用GridBagLayout。

我在JPanel中有3个组件,其中GridBagLayout是JPanel的LayoutManager,并在这3个组件上使用GridBagConstraints。

使用当前代码(如下所示),3个元素将正确显示在面板上。问题是,第一个组件是一个JLabel,它有时很长,如果是这样的话,它将扩展并使其他两个组件变小。

我的目标是拥有一个GridBagLayout为1行4列的JPanel,其中第一个元素占据前2列,其他2个元素占据剩下的2列,并且这些元素不会扩展到它们的列之外。

代码语言:javascript
运行
复制
private static void setConstraints(GridBagConstraints constraints, int gridx, int gridy, int weightx, Insets insets) {
    constraints.gridx = gridx;
    constraints.weightx = weightx;
    constraints.insets = insets;
}

gridBagLayout = new GridBagLayout();
constraints = new GridBagConstraints();
centerPanel = new JPanel(gridBagLayout);

constraints.fill = GridBagConstraints.HORIZONTAL;
fileNameLabel = new JLabel("Resolving: '" + EngineHelpers.trimStringToFitPanel(urlTextField.getText(), 70) + "'");
setConstraints(constraints, 0, 0, 2, new Insets(0, 5, 5, 0));
gridBagLayout.setConstraints(fileNameLabel, constraints);
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
setConstraints(constraints, 1, 0, 1, new Insets(0, 5, 5, 0));
gridBagLayout.setConstraints(progressBar, constraints);
cancelDownloadButton = new JButton("Cancel");
setConstraints(constraints, 2, 0, 1, new Insets(0, 0, 0, 0));
gridBagLayout.setConstraints(cancelDownloadButton, constraints);

centerPanel.add(fileNameLabel);
centerPanel.add(progressBar);
centerPanel.add(cancelDownloadButton);

提前感谢大家,很抱歉问了这个愚蠢的问题!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-20 19:53:17

您可能希望将按钮和进度条的weightx设置为0。对于标签,将权重设置为1。这将使按钮和进度条完全不会扩展,并让进度条占据所有额外的空间。

另外,将进度条上的gridwidth约束设置为2,这样它就实际使用了2列。

最后,根据放置centerPanel的位置,它可能不会实际展开以填充容器。如果将centerPanel放在具有BorderLayout的父级中,则它应该展开。为了确保这一点,您可以使用centerPanel.setBorder(BorderFactory.createLineBorder(Color.RED))添加边框以进行调试。这在按钮、标签和进度条上也很有用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12987929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档