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...
Surround the string with <html></html> and break the lines with <br/> . just a little correction: use <br /> instead of just <br> ... this is recommended way of doing it (to not miss any closing tags)...
Make a separate JPanel for each line, and set the dimensions to fit each word: JLabel wordlabel = new JLabel("Word"); JPanel word1 = new JPanel(); word1. setPreferredSize(new Dimension(#,#);
As per @darren's answer, you simply need to wrap the string with <html> and </html> tags: myLabel. setText("<html>"+ myString +"</html>"); You do not need to hard-code any break tags.
Surround the string with <html></html>
and break the lines with <br/>
.
JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With