我目前有一个 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);
}
}
示例代码似乎工作正常,但会不会出现问题?
最佳答案
您可以使用带有 GridLayout 的 JPanel,在其构造函数中传递 0 行和 2 列:
JPanel panel = new JPanel(new GridLayout(0 ,2));
这意味着当您向面板添加组件时,面板的高度会增加,同时始终保持 2 列
添加 JButton 的代码将像这样简单:
for(int i = 0; i < jButtonList.size(); i++) {
panel.add(jButtonList.get(i));
}
关于java - 如何添加在两列之间动态平均分配的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12392878/