How can I display a newline in JLabel
?
For example, if I wanted:
Hello World!
blahblahblah
This is what I have right now:
JLabel l = new JLabel("Hello World!\nblahblahblah", SwingConstants.CENTER);
This is what is displayed:
Hello World!blahblahblah
Forgive me if this is a dumb question, I'm just learning some Swing basics...
This question is related to
java
user-interface
swing
formatting
jlabel
JLabel is actually capable of displaying some rudimentary HTML, which is why it is not responding to your use of the newline character (unlike, say, System.out).
If you put in the corresponding HTML and used <BR>
, you would get your newlines.
Thanks Aakash for recommending JIDE MultilineLabel. JIDE's StyledLabel is also enhanced recently to support multiple line. I would recommend it over the MultilineLabel as it has many other great features. You can check out an article on StyledLabel below. It is still free and open source.
You can try and do this:
myLabel.setText("<html>" + myString.replaceAll("<","<").replaceAll(">", ">").replaceAll("\n", "<br/>") + "</html>")
The advantages of doing this are:
<br/>
, without fail.<
and >
with <
and >
respectively, preventing some render havoc.What it does is:
"<html>" +
adds an opening html
tag at the beginning.replaceAll("<", "<").replaceAll(">", ">")
escapes <
and >
for convenience.replaceAll("\n", "<br/>")
replaces all newlines by br
(HTML line break) tags for what you wanted+ "</html>"
closes our html
tag at the end.P.S.: I'm very sorry to wake up such an old post, but whatever, you have a reliable snippet for your Java!
You can do
JLabel l = new JLabel("<html><p>Hello World! blah blah blah</p></html>", SwingConstants.CENTER);
and it will automatically wrap it where appropriate.
You can use the MultilineLabel component in the Jide Open Source Components.
Source: Stackoverflow.com