File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Can't get label to center horizontally. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Can Watch "Can New topic

Can't get label to center horizontally.

Paul Carter
Ranch Hand

Joined: Sep 20, 2006
Posts: 57
Using the code below to try create a new label with text that is centre aligned on the form, but it always appeared left aligned.

Am I missing something?

Thanks in advance


setLayout(new GridLayout(3, 1));

towerLCD = new JLabel("LCD Goes Here");
add(towerLCD, BorderLayout.NORTH);
Tim LeMaster
Ranch Hand

Joined: Aug 31, 2006
Posts: 226

setVerticalTextPosition and setHorizontalTextPosition act upon the text of a JLabel in relation to its image. This JLabel appears to have no image, so this won't have any effect.

Look at setHorizontalAlignment(). This will center the text in the area taken up by the JLabel. That doesn't mean the JLabel is in the center of the form. Thats up to the layout manager and the other components on the container. Welcome to the wonderful world of layout managers.

This probably belongs in the Swing Forum.

Edited - cause I can't spell
[ October 11, 2006: Message edited by: Tim LeMaster ]
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
use the JLabel constructor that has an alignment parameter
I agree. Here's the link:
subject: Can't get label to center horizontally.
It's not a secret anymore!