Java align JLabel in center of JPanel

Bassetts picture Bassetts · Mar 17, 2011 · Viewed 54.5k times · Source

I have a bar at the top of my application that has a number of buttons either side of a JLabel. The button's visibility is dependent upon the current task a user is carrying out and one of the button's text may also change depending on the current state.

What I would like to do is have a number of buttons stick to the left of the JPanel, the JLabel's center to be in the very center of the JPanel and the rest of the buttons to be to the right of the JPanel.

So far I have managed to get the buttons sticking to the left and the right using various methods and layout managers but I cannot get the JLabel's center to be in the dead center of the JPanel. The best I have managed to get is the label near enough to the center but it would then move around as the buttons are set to visible or their text changes.

Is it possible to force the JLabel to remain dead center?

Note: the buttons will never become big enough to meet either edge of the JLabel, so that is not a problem.

Answer

MeBigFatGuy picture MeBigFatGuy · Mar 17, 2011

You could also use a BoxLayout, with X_AXIS layout, and add to the container

Edit: Here's an example

panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createHorizontalGlue());
panel.add(innerPanel);
panel.add(Box.createHorizontalGlue());