Java swing: Multiline labels? [duplicate]

2019-01-23 22:23发布

Possible Duplicate:
Multiline text in JLabel

I want to do this:

JLabel myLabel = new JLabel();
myLabel.setText("This is\na multi-line string");

Currently this results in a label that displays

This isa multi-line string

I want it to do this instead:

This is
a multi-line string

Any suggestions?

Thank you


EDIT: Implemented solution

In body of method:

myLabel.setText(convertToMultiline("This is\na multi-line string"));

Helper method:

public static String convertToMultiline(String orig)
{
    return "<html>" + orig.replaceAll("\n", "<br>");
}

7条回答
Explosion°爆炸
2楼-- · 2019-01-23 22:45

You can use HTML in JLabels. To use it, your text has to start with <html>.

Set your text to "<html>This is<br>a multi-line string" and it should work.

See Swing Tutorial: JLabel and Multiline label (HTML) for more information.

查看更多
Lonely孤独者°
3楼-- · 2019-01-23 22:45

Another easy way (but changes the text style a bit) is to use a <pre></pre> html block.

This will persist any formatting the user entered if the string you are using came from a user input box.

Example:

JLabel label = new JLabel("<html><pre>First Line\nSecond Line</pre></html>"); 
查看更多
We Are One
4楼-- · 2019-01-23 22:47

JLabel can accept html code. Maybe you can try to use the <br> tag.

Example:

JLabel myLabel = new JLabel();
myLabel.setText("<html> This is a <br> multi-line string </html>");
查看更多
Animai°情兽
5楼-- · 2019-01-23 22:52

The direct procedure of writing a multi-line text in a jlabel is:

JLabel label = new JLabel("<html>First Line<br>Second Line</html>"); 
查看更多
够拽才男人
6楼-- · 2019-01-23 22:56

The problem with using html in JLabel or any Swing component is that you then have to style it as html, not with the usual setFont, setForeground, etc. If you're ok with that, fine.

Otherwise you can use something like MultilineLabel from JIDE, which extends JTextArea. It's part of their open source Commom Layer.

查看更多
爷、活的狠高调
7楼-- · 2019-01-23 22:59
public class JMultilineLabel extends JTextArea{
    private static final long serialVersionUID = 1L;
    public JMultilineLabel(String text){
        super(text);
        setEditable(false);  
        setCursor(null);  
        setOpaque(false);  
        setFocusable(false);  
        setFont(UIManager.getFont("Label.font"));      
        setWrapStyleWord(true);  
        setLineWrap(true);
    }
} 

It totally looks the same for me, but its ugly

查看更多
登录 后发表回答