Image

Imagesparkymark wrote in Imagejava_dev

Centering a JLabel in Swing: help please!

I'm sure this should be simple but I can't figure it out.

I have two JLabels that I want to display on the same horizontal line. The first should be at the left extreme of the line, and the second one in the centre.

I can't simply use BorderLayout because, as the canonical example at http://java.sun.com/docs/books/tutorial/uiswing/layout/border.html shows, "Button 2" isn't actually in the centre, its just in between buttons 3 and 5 taking up as much room as possible. Buttons 3 and 5 are not the same size so the text of Button 2, even when horizontally-aligned to be in the centre of the button, is still not in the centre of the entire line.

Some sort of horizontal-glue looks appropriate, but there's no way to get something into the centre with Boxlayout is there?

I would hope I don't I need to do absolute positioning (or make an invisible JLabel the same size of the first one to put at the LINE_END to force the CENTER into the centre: that looks desperate).