Search code examples
javaswingcenteringboxlayout

Centering a JButton using Box Layout.X_AXIS


I have a JPanel that can have either 1 or 2 buttons, depending on what's going on in the program at the time. I'm using Box Layout.X_AXIS to line up the 2 buttons configuration, and it works great. When I switch to 1 button however, the single button is on the far left of the window. I've tried a bunch of different things to get the button centered, but the only thing that seems to work is this:

JButton yesBtn = new JButton("Continue");
btnPane.setLayout(new BoxLayout(btnPane, BoxLayout.Y_AXIS));
yesBtn.setAlignmentX(Component.CENTER_ALIGNMENT);

The problem with this is that the vertical location of the button changes doing it this way, so it doesn't match where the 2 buttons would sit vertically. Is there a way to center the button using the X_AXIS layout?


Solution

  • I've tried a bunch of different things to get the button centered,

    The easiest way is to add "glue" BEFORE the first component and AFTER the last component. Then it will work for 1 component or multiple components.

    Read the section from the Swing tutorial on Invisible Components as Filler for more information and examples.