GridBagLayout调整面板大小

时间:2018-03-24 18:49:15

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

我已经阅读了几篇关于这个主题以及文档的文章,但我似乎无法解决我的问题。

我创建了一个需要调整大小的GUI;但是,我想保持每行有3个JTextField。

我尝试过调整weightx,但没有成功。

以下是我的代码片段:

    JPanel panelMain = new JPanel();
    getContentPane().add(panelMain);

    JPanel panelForm = new JPanel(new GridBagLayout());
    panelMain.add(panelForm);

    //JScrollPane scrollpane = new JScrollPane(panelForm);
    //panelMain.add(scrollpane);



    GridBagConstraints c = new GridBagConstraints();

    c.gridx = 0;
    c.gridy = 0;

    // Row 1
    buttonAddCourses = new JButton("Add Credit Hours");
    buttonAddCourses.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            c.gridx = 0;
            c.weightx = 0.2;
            for(int i = 0; i < 15; i++) {
                JTextField newTextField = new JTextField(20);
                listTextFields.add(newTextField);
                panelMain.add(newTextField,c);
                c.gridy++;

            }

            panelMain.validate();
            panelMain.repaint();
        }

    });
    panelForm.add(buttonAddCourses, c);
    c.gridx++;

调整大小之前:!https://imgur.com/a/XCUtJ

调整大小后: !https://imgur.com/a/a4Qo4

1 个答案:

答案 0 :(得分:0)

JPanel panelMain = new JPanel(); // <- gets a FlowLayout by default
// ..
JPanel panelForm = new JPanel(new GridBagLayout()); // panel with GBL
// ...
    panelMain.add(newTextField,c); // No, this should be panelForm.add(..);