删除一些组件后错误的安排

时间:2013-12-15 10:33:40

标签: java user-interface awt layout-manager gridbaglayout

我对(我想的)布局管理器有一点问题。 我正在使用GridBagLayout来安排我的组件但是在删除整个集之后它会搞砸了。

这是代码:

 public TabBody()
{
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.WEST;
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(5, 5, 5, 5);
    nameField = new JTextField(20);
    closeButton = new JButton("x");
    closeButton.setMargin(new Insets(0, 0, 0, 0));
    closeButton.setPreferredSize(new Dimension(18, 18));
    closeButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            removeAll();
        }
    });
    amountField = new JTextField(20)
    {
        @Override
        public void processKeyEvent(KeyEvent ev)
        {
            char c = ev.getKeyChar();

             if (c > 48 && c < 57 || c == 8 || ev.getKeyCode() == KeyEvent.VK_LEFT || ev.getKeyCode() == KeyEvent.VK_RIGHT)
             {
                super.processKeyEvent(ev);
             }

        }
    };
    unitsBox = new JComboBox(units);
    unitsBox.setSelectedIndex(3);
    c.gridx++;
    add(new JLabel("Product name"), c);
    c.gridx++;
    add(new JLabel("Amount"), c);
    c.gridx++;
    add(new JLabel("Unit"), c);
    c.gridy++;
    c.gridx++;
    add(new JLabel("="), c);
    c.gridx++;
    add(new JLabel("KCal"), c);

    c.gridx = 0;
    add(closeButton, c);
    c.gridx++;
    add(nameField, c);
    c.gridx++;
    add(amountField, c);
    c.gridx++;
    add(unitsBox, c);
}

以下是我添加几组组件时的外观:http://i.imgur.com/ReQumkr.jpg 以下是我删除部分内容时的外观:http://i.imgur.com/3cWCYX0.jpg 如你所见,其中一些甚至不在X轴。 谢谢你提前。

0 个答案:

没有答案