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]

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 >

[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]