GridBagLayout在添加第二个元素时不起作用

时间:2014-10-31 04:47:19

标签: java swing gridbaglayout

我刚学习GridBagLayout。当我在布局中添加JTextField时,一切似乎都消失了

//      final JTextField textField = new JTextField("textField");
//      addComponentToGridbag(textField, 0,0,1,1);

        JButton button = new JButton("Button");
        addComponentToGridbag(button, 1,0,1,1);

如果我将前两行注释掉,我会得到这个,除了没有文本字段(当然)之外没问题:

enter image description here

但我希望文本字段直接显示在按钮上方,因此我取消注释这两行。然后我明白了(注意我的按钮不仅消失了,我的顶部和底部面板也是如此):

enter image description here

发生了什么事?如何在不丢失其他内容的情况下显示文本字段?谢谢!

以下是整个班级:

public class GUI {

    private JFrame frame;
    private JPanel topPanel = new JPanel();
    private JPanel bottomPanel = new JPanel();
    private GridBagLayout layout = new GridBagLayout();
    private GridBagConstraints constraints = new GridBagConstraints();
    private JPanel centerPanel = new JPanel();

    public GUI() {

        makeMainFrame();
        makePanels();
        bodyLayout();

        JLabel title = new JLabel("Dashboard");
        topPanel.add(title);

        JButton btnExit = new JButton("Exit");
        bottomPanel.add(btnExit);
    }

    private void bodyLayout() {

        centerPanel.setLayout(layout);

        final JTextField textField = new JTextField("textField");
        addComponentToGridbag(textField, 0,0,1,1);

        JButton btnFetchMetaData = new JButton("Button");
        addComponentToGridbag(btnFetchMetaData, 1,0,1,1);
    }

    private void addComponentToGridbag(Component component, int row, int column, int width, int height) {
        constraints.gridx = column;
        constraints.gridy = row;
        constraints.gridwidth = width;
        constraints.gridheight = height;
        layout.setConstraints(component, constraints);
        centerPanel.add(component);
    }

    private void makeMainFrame() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = (int) (screenSize.height * 0.75);
        int width = (int) (screenSize.width * 0.75);

        frame = new JFrame();
        frame.setVisible(true);
        frame.setTitle("Learning Java Swing");
        frame.setSize(width, height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.getContentPane().setLayout(new BorderLayout(0, 0));
    }

    private void makePanels() {
        frame.getContentPane().add(topPanel, BorderLayout.NORTH);
        frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);

        centerPanel.setBackground(Color.RED);
        centerPanel.setOpaque(true);
        frame.getContentPane().add(centerPanel, BorderLayout.CENTER);

    }

1 个答案:

答案 0 :(得分:1)

重用相同的GridBagConstraints对象可能是个问题。尝试始终在addComponentToGridbag方法

中创建新的GridBagConstraints