【发布时间】:2015-02-09 18:58:06
【问题描述】:
在带有 BorderLayout 的 JFrame 中,我在窗口底部有一个“控制面板”(带有按钮和东西)。在这个“控制面板”的 JPanel 中,我想使用 GridBagLayout。 这是我现在的结果。
我正在考虑将布局划分为 3 行 x 8 列的表格。 在此配置中,“+”符号应该只占一个正方形,并且所有按钮都应该填满面板。
代码是这样的:
buttonsPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
removeCost = new JButton("-");
c.gridx = 5;
c.gridy = 0;
buttonsPanel.add(removeCost, c);
addCost = new JButton("+");
c.gridx = 7;
c.gridy = 0;
buttonsPanel.add(addCost, c);
text = new JLabel("Incasso");
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
buttonsPanel.add(text, c);
cost = new JTextArea();
cost.setBorder(BorderFactory.createLineBorder(Color.black, 1, true));
cost.setPreferredSize(new Dimension(80, 18));
c.gridx = 5;
c.gridy = 1;
c.gridwidth = 3;
buttonsPanel.add(cost, c);
cancel = new JButton("Cancella");
c.anchor = GridBagConstraints.LINE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 3;
c.insets = new Insets(0, 2, 2, 30);
buttonsPanel.add(cancel, c);
enter = new JButton("Accetta");
c.anchor = GridBagConstraints.LINE_END;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 5;
c.gridy = 2;
c.gridwidth = 3;
c.insets = new Insets(0, 30, 2, 2);
buttonsPanel.add(enter, c);
我做错了什么?
【问题讨论】:
-
您必须按列、行、布局顺序指定 GridBagLayout 的 Swing 组件。您可以使用 Insets 在组件之间创建空间。
-
cost = new JTextArea(); .. cost.setPreferredSize(new Dimension(80, 18));应该更像cost = new JTextArea(3,40);。见Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?(是的。) -
您已经设置了 gridWidth 属性,但在再次使用约束之前没有重置它,请注意
-
@MadProgrammer:前两个组件的网格宽度未设置,然后为每个组件设置。所以我认为这不是问题
标签: java swing whitespace layout-manager gridbaglayout