aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Can Watch "Can New topic
Author

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

Paul.

setLayout(new GridLayout(3, 1));

towerLCD = new JLabel("LCD Goes Here");
towerLCD.setVerticalTextPosition(JLabel.CENTER);
towerLCD.setHorizontalTextPosition(JLabel.CENTER);
towerLCD.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Can't get label to center horizontally.