在带有BorderLayout的JFrame中,我在窗口底部有一个“控制面板”(带有按钮和东西)。在这个“控制面板”的JPanel中,我想使用GridBagLayout。 这是我现在的结果。如何在GridBagLayout中的组件之间放置空格?
我想在一个3行×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在组件之间创建空间。 – 2015-02-09 19:19:24
查看[这个答案](http://stackoverflow.com/a/17876938/418556)[在Swing GUI中提供空白区域](http://stackoverflow.com/questions/17874717/providing-white-space- IN-A-Swing的GUI)。 – 2015-02-09 20:32:51
'cost = new JTextArea(); .. cost.setPreferredSize(new Dimension(80,18));'应该更像'cost = new JTextArea(3,40);'。请参阅[我是否应避免使用Java Swing中的set(Preferred | Maximum | Minimum)Size方法?](http://stackoverflow.com/q/7229226/418556)(是) – 2015-02-09 20:35:00