我使用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);
}
我希望看到我的组件布局如下:
然而,我实际看到的是:
即。缺少“浏览...”按钮!这是为什么?
答案 0 :(得分:2)
从你的绘图中,我猜你根本不想要相对宽度。看起来您希望标签和按钮是他们的首选尺寸,并且JTextField要拉伸以占据标签和按钮未使用的所有宽度。
正如camickr建议的那样,您应该通过使用列数来初始化JTextField来为JTextField提供有意义的首选大小,例如new JTextField(20)
。
然后,您可以利用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 ...等。