有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何添加在两列之间动态平均分配的组件?

我目前有一个JButton数组,我想把它们放在我的JPanel上,分成两列,平均分割。因此,如果数组中有8个按钮,那么左栏中有4个按钮,右栏中有4个按钮。但是,如果数组中有7个按钮,则左栏将有4个按钮,右栏将有3个按钮

我为这样一个场景创建了一些基本逻辑,并想看看我编写的代码中是否有逻辑错误(或者是更好的方法)

这是我想出的代码

public class SwingTest {

    public static void main(String[] args) {
        JFrame frame = new JFrame();

        JButton b1 = new JButton();
        b1.setText("Button1");

        JButton b2 = new JButton();
        b2.setText("Button2");

        JButton b3 = new JButton();
        b3.setText("Button3");

        JButton b4 = new JButton();
        b4.setText("Button4");

        JButton b5 = new JButton();
        b5.setText("Button5");

        JButton b6 = new JButton();
        b6.setText("Button6");

        ArrayList<JButton> jButtonList = new ArrayList();
        jButtonList.add(b1);
        jButtonList.add(b2);
        jButtonList.add(b3);
        jButtonList.add(b4);
        jButtonList.add(b5);
        jButtonList.add(b6);

        JPanel panel = new JPanel();
        panel.setLayout(new java.awt.GridBagLayout());

        double halfList = Math.ceil((jButtonList.size() / 2.0));
        int gridX = 0, gridY = 0;

        for(int i = 0; i < jButtonList.size(); i++) {
            GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();

            if(gridY == (int)halfList) {
                gridX++;
                gridY = 0;
            }
            gridBagConstraints.gridx = gridX;
            gridBagConstraints.gridy = gridY;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            gridBagConstraints.weightx = 1.0;
            gridBagConstraints.weighty = 1.0;
            gridBagConstraints.insets = new java.awt.Insets(1, 0, 1, 0);
            panel.add(jButtonList.get(i), gridBagConstraints);
            gridY++;
        }
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

示例代码似乎工作得很好,但是否会出现可能出现问题的情况


共 (2) 个答案

  1. # 1 楼答案

    为此使用GridBagLayout似乎是一个很好的计划

    不过,我会稍微清理一下按钮构建代码。如果您需要100个按钮,会发生什么?手动添加100个按钮似乎不是一个好主意。我会有一个参数化的方法来构建并返回一个按钮和一个循环,用于将按钮添加到ArrayList

  2. # 2 楼答案

    您可以使用带有GridLayout的JPanel,该JPanel在其构造函数中传递0行,包含2列:

    JPanel panel = new JPanel(new GridLayout(0 ,2));
    

    这意味着在向面板添加构件时,面板的高度将增加,同时始终保持两列

    添加jbutton的代码如下所示:

    for(int i = 0; i < jButtonList.size(); i++) {
        panel.add(jButtonList.get(i));
    }