Centering Text within JLabel

I am trying to figure out a way to center the text within a JLabel. I trying to set a specific size of the label, and then center the text in the very middle (horizontally) of that label. I have tried many different methods from this forum and other places on Google, but none of them have had any effect. For example:

label =new JLabel ("<html>blah, blah, blah, blahblah, blah...</html>");

// HTML tags make the lines wrap.

label.setHorizontalAlignment(JLabel.CENTER);

label.setPreferredSize (new Dimension (84, 48));

The text remains aligned left within the label. Is there a way to get it to center within the label?

[792 byte] By [purusa] at [2007-10-2 18:26:06]
# 1
Don't use HTML:JLabel label = new JLabel("Some Text");label.setPreferredSize(new Dimension(400, 16) );label.setHorizontalAlignment(JLabel.CENTER);
camickra at 2007-7-13 19:47:11 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thanks, that centers them nicely. Unfortunately, removing the HTML tags gets rid of the line wrap, causing the line to continue off out of the defined label space rather than wrapping. Is there anyway to have the lines wrap and center in the label?
purusa at 2007-7-13 19:47:11 > top of Java-index,Desktop,Core GUI APIs...
# 3
Use a JTextPane. Set the paragraph attributes to be centered. You can play with the foreground and background colors to make it look like a label. Here is a simple example: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=342068
camickra at 2007-7-13 19:47:11 > top of Java-index,Desktop,Core GUI APIs...
# 4
I found that including centering tags withing the HTML tags worked nicely to center the text. That way I can have wrapping lines that are centered. :)
purusa at 2007-7-13 19:47:11 > top of Java-index,Desktop,Core GUI APIs...
# 5

[nobr]what version are you using?

your posted code works OK in 1.5.0_05

import java.awt.*;

import javax.swing.*;

class Testing extends JFrame

{

public Testing()

{

setSize(300,100);

setLocation(400,300);

setDefaultCloseOperation(EXIT_ON_CLOSE);

JPanel p = new JPanel();

JLabel label = new JLabel("<html>line 1<br>line 2</html>");

label.setHorizontalAlignment(JLabel.CENTER);

label.setPreferredSize (new Dimension (84, 48));

label.setBorder(BorderFactory.createLineBorder(Color.black));

p.add(label);

getContentPane().add(p);

}

public static void main(String[] args){new Testing().setVisible(true);}

}

[/nobr]

Michael_Dunna at 2007-7-13 19:47:11 > top of Java-index,Desktop,Core GUI APIs...
# 6
I'm using build 1.5.0_06-112 on Mac OSX 10.4.6. It worked fine, it just wasn't centering the text within the label. Adding html center tags within the html tags did the job nicely though.
purusa at 2007-7-13 19:47:11 > top of Java-index,Desktop,Core GUI APIs...