Reputation: 926
I currently have an array of JButtons and I want to place them on my JPanel in two columns, split evenly. So if there are 8 buttons in the array there would be 4 buttons in the left column and 4 buttons in the right column. However, if there are 7 buttons in the array, the left column would have 4 buttons and the right column would have 3 buttons.
I went about and create some basic logic for such a scenario and wanted to see if there was any logic error in the code I made (or perhaps a better way of doing this).
Here is the code I've come up with
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);
}
}
The sample code seems to work fine, but will there ever be a case where it might hiccup?
Upvotes: 1
Views: 2219
Reputation: 32391
Using a GridBagLayout
for this seems to be a good plan.
However, I would clean up the button building code a little bit. What happens if you will need 100 buttons? Manually adding 100 buttons doesn't seem to be a good idea. I would have a parametrized method for building and returning a button and a loop for adding the buttons to your ArrayList
.
Upvotes: 1
Reputation: 348
You may use a JPanel with GridLayout passing 0 lines in its constructor with 2 columns:
JPanel panel = new JPanel(new GridLayout(0 ,2));
It means that the panel will increase in height when you add components to it, while keeping always 2 columns
The code to add the JButtons will be as simple as this:
for(int i = 0; i < jButtonList.size(); i++) {
panel.add(jButtonList.get(i));
}
Upvotes: 4