GridBag不显示行中的所有组件

时间:2017-01-26 15:26:11

标签: java swing gridbaglayout

我使用JPanel实施了GridBagLayout,如下所示:

fileSelectionDetails = new JPanel();
fileSelectionGridBagLayout = new GridBagLayout();
fileSelectionDetails.setLayout(fileSelectionGridBagLayout);


JLabel lblFile1 = new JLabel("File 1:");
JTextField txtFile1Path = new JTextField();    
JButton btnBrowseFile1 = new JButton("Browse...");

addComponentToFileSelectionGrid(lblFile1, 0, 0, 1, 1, 20, 100, GridBagConstraints.NONE, GridBagConstraints.WEST);
addComponentToFileSelectionGrid(txtFile1Path, 1, 0, 3, 1, 60, 100, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
addComponentToFileSelectionGrid(btnBrowseFile1, 2, 0, 1, 1, 20, 100, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);

private void addComponentToFileSelectionGrid(Component component, int gridX, int gridY,
                            int gridWidth, int gridHeight, int weightX, 
                            int weightY, int fill, int anchor) {

    GridBagConstraints constraint = new GridBagConstraints();
    constraint.gridx = gridX;
    constraint.gridy = gridY;
    constraint.gridwidth = gridWidth;
    constraint.gridheight = gridHeight;
    constraint.weightx = weightX;
    constraint.weighty = weightY;       
    constraint.fill = fill;
    constraint.anchor = anchor;
    fileSelectionGridBagLayout.setConstraints(component, constraint);
    fileSelectionDetails.add(component);
}

我希望看到我的组件布局如下:

enter image description here

然而,我实际看到的是:

enter image description here

即。缺少“浏览...”按钮!这是为什么?

2 个答案:

答案 0 :(得分:2)

从你的绘图中,我猜你根本不想要相对宽度。看起来您希望标签和按钮是他们的首选尺寸,并且JTextField要拉伸以占据标签和按钮未使用的所有宽度。

正如camickr建议的那样,您应该通过使用列数来初始化JTextField来为JTextField提供有意义的首选大小,例如new JTextField(20)

然后,您可以利用GridBagLayout和GridBagConstraints的一些有用方面:

  • gridx和gridy的默认值为RELATIVE,这意味着您添加的每个组件都放在最后添加的组件的右侧。这正好恰好是你想要的。因此,您根本不应该设置gridx或gridy。
  • gridwidth和gridheight的默认值为1.这就是您想要的。 GridBagLayout单元格非常灵活,因此将一个组件的网格宽度设置为3 使其宽度比网格宽度为1的组件宽三倍。单元格的宽度或单元格的跨度完全取决于它的大小包含。
  • 将组件添加到GridBagLayout时,GridBagConstraints对象将克隆在GridBagLayout中。这意味着您可以安全地重复使用相同的GridBagConstraints对象,只更改需要更改的字段。

有了这些知识,您的代码可以简化为:

fileSelectionDetails = new JPanel(new GridBagLayout());

JLabel lblFile1 = new JLabel("File 1:");
JTextField txtFile1Path = new JTextField(20);
JButton btnBrowseFile1 = new JButton("Browse\u2026");

txtFile1Path.setMinimumSize(txtFile1Path.getPreferredSize());

GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;

constraints.weight = 0;
fileSelectionDetails.add(lblFile1, constraints);
constraints.weight = 1;
fileSelectionDetails.add(txtFile1Path, constraints);
constraints.weight = 0;
fileSelectionDetails.add(btnBrowseFile1, constraints);

答案 1 :(得分:1)

为txtFile1Path定义gridWidth = 3,但在gridX = 2处添加btnBrowseFile1。你必须设置addComponentToFileSelectionGrid(btnBrowseFile1,4 ...等。