Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can't get label to center horizontally.

 
Paul Carter
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use the JLabel constructor that has an alignment parameter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic