Java JLabel, break text to next line?

user569322 picture user569322 · Feb 15, 2012 · Viewed 13.3k times · Source

It's been awhile since I asked a question!

I'm developing an application in Java where JLabels are used. Anyway, as you may or may not be able to see from the picture below, the text that says Category Test gets cut off and ends up saying Categor... instead. Is there any way that I can "break" the text once it fills up the width of the label? Here is the image:

enter image description here

What I did

I used a JTextPane like so:

    JTextPane text = new JTextPane();
    SimpleAttributeSet attr = new SimpleAttributeSet();   

    StyleConstants.setAlignment(attr, StyleConstants.ALIGN_CENTER);  

    pane.add(text, c);

Then I added my text, but thanks anyway!

Answer

Jeffrey picture Jeffrey · Feb 15, 2012

JLabels can't do that by default. But JLabels have some support for html, so a JLabel with the text <html>First Line<br />Second Line</html> would show up on two lines.

If you want a component that can split the lines by itself, take a look at JTextArea.