我目前有一个 JButtons 数组,我想将它们放在我的 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);
}
}
示例代码似乎可以正常工作,但是否会出现打嗝的情况?