Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to center a JLabel on a JFrame?

800308Dec 21 2007 — edited Dec 22 2007
Hi,

I would like to display some text centered on a JFrame, without just drawing the string directly on the content pane...

A JLabel seemed like a good place to start... I've been stuck for over an hour trying to center the label on the frame, without also resorting to setLayout(null);

I've tried a BorderLayout... I can't figure out how to stop the JLabel expanding to fill the JFrame.

I then tried and rejected GridBagLayout really quickly... for the same issues.

Everything I read says setLayout(null) is BAD, but (so far) it's the only thing I understand... I've been hacking at this for about an hour, and I'm ready to spit!

... and it's starting to make me feel inadequate. I mean, at face value this is a simple requirement... WTF is everything in Swing to bluddy complicated? Sheesh! It's frustrating! It's NOT just me it is?

I would also like (if possible) to center the label's text both vertically and horizontally within the label.
 but the methods:
jLabel.setHorizontalTextPosition(JLabel.CENTER);
jLabel.setVerticalTextPosition(JLabel.CENTER);
don't appear to do anything!

Cheers & Thanx. Keith.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 19 2008
Added on Dec 21 2007
10 comments
7,201 views