【发布时间】:2012-10-10 21:00:46
【问题描述】:
我已经尝试了所有组合并查看了所有文档,但我不知道如何使用 GridBagLayout。
我在 JPanel 中有 3 个组件,其中 GridBagLayout 是 JPanel 的 LayoutManager,并在 3 个组件上使用 GridBagConstraints。
使用当前代码(如下所示),3 个元素正确显示在面板上。问题是第一个组件是一个有时很长的 JLabel,如果是这种情况,那么它会扩展并使其他 2 个组件更小。
我的目标是让 JPanel 的 GridBagLayout 为 1 行 4 列,其中第一个元素占据前 2 列,其他 2 个元素占据剩余的 2 列,并且这些元素不要展开出他们的专栏。
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);
先谢谢大家了,抱歉这个愚蠢的问题!
【问题讨论】:
标签: java layout-manager gridbaglayout