【问题标题】:GridBagLayout Resizing PanelGridBagLayout 调整大小面板
【发布时间】:2018-03-24 18:49:15
【问题描述】:

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

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

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

这是我的代码的 sn-p:

    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

【问题讨论】:

  • 请创建并发布一个有效的minimal reproducible example
  • I have created a GUI that needs to be resizeable; however, I would like to maintain that there are 3 JTextFields for each row. - GridBagLayout 不会根据可用空间将组件“包装”到新行。调整大小永远不会改变一行中的组件数量。它只会调整组件的大小。你的要求真的不是很清楚。

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


【解决方案1】:
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(..);

【讨论】: