Below panel has BoxLayout and the button's at the bottom are not occupying width of the panel and instead there is gap on the left and right side.
JPanel panel = new JPanel();
BoxLayout boxlayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(boxlayout);
JPanel framesPanel[] = new JPanel[8];
for(int i=0;i<8;i++) {
framesPanel[i] = new JPanel();
framesPanel[i].setLayout(new BoxLayout(framesPanel[i], BoxLayout.X_AXIS));
JButton jb1 = new JButton("Button 1");
jb1.setAlignmentX(Component.LEFT_ALIGNMENT);
JButton jb2 = new JButton("Button 2");
jb2.setAlignmentX(Component.LEFT_ALIGNMENT);
JButton jb3 = null;
framesPanel[i].add(jb1);
framesPanel[i].add(jb2);
if (i < 6) {
jb3 = new JButton("Button 3");
jb3.setAlignmentX(Component.LEFT_ALIGNMENT);
framesPanel[i].add(jb3);
}
panel.add(framesPanel[i]);
}
// Set size for the frame
panel.setSize(300, 300);
frame.setSize(300, 300);
// Set the window to be visible as the default to be false
frame.add(panel);
I have tried with setAlignmentX(Component.LEFT_ALIGNMENT) but this doesn't seem to have any effect.
A BoxLayout
respects the maximum size of a component.
The buttons maximum size is the same as its preferred size.
When you create the buttons you could do something like:
JButton button = new JButton(...);
Dimension maximum = button.getMaximumSize();
maximum.width = Integer.MAX_VALUE;
button.setMaximumSize( maximum );
Note:
This is only a quick fix that will work if you never change the Font size of the button. For a proper solution you should really creat a custom button that extends JButton and override the getMaximumSize()
method to return the above size. Then this will work if the properties of the button are changed dynamically.