Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "word wrap" property for JLabel?

Tags:

java

swing

jlabel

I am displaying some text in a JLabel. Basically I am generating that text dynamically, and then I apply some HTML tags (e.g., BR and B) to format the text. Finally I assign this formatted text to my JLabel.

Now I want my Jlabel to automatically wrap the text to the next line when it reaches the end of screen, like the "Word Wrap" feature in Note Pad.

How can I do that?

like image 965
Jame Avatar asked Oct 22 '11 18:10

Jame


People also ask

How do you wrap text in a JLabel?

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.

How do you wrap text in Java?

The first wrap() method takes the String to wrap as its first argument and the wrap length as its second argument. The second wrap() method takes for arguments. The first is the String to wrap and the second is the wrap length. The third is the newline characters to use when a line is wrapped.

What can a JLabel not do?

JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel can display text, image or both . JLabel is only a display of text or image and it cannot get focus .


2 Answers

A width can be set for the body using HTML styles (CSS). This in turn will determine the number of lines to render and, from that, the preferred height of the label.

Setting the width in CSS avoids the need to compute where line breaks should occur in (or the best size of) the label.

import javax.swing.*;  public class FixedWidthLabel {      public static void main(String[] srgs) {         final String s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla urna. Donec sit amet risus nisl, a porta enim. Quisque luctus, ligula eu scelerisque gravida, tellus quam vestibulum urna, ut aliquet sapien purus sed erat. Pellentesque consequat vehicula magna, eu aliquam magna interdum porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed sollicitudin sapien non leo tempus lobortis. Morbi semper auctor ipsum, a semper quam elementum a. Aliquam eget sem metus.";         final String html = "<html><body style='width: %1spx'>%1s";          Runnable r = () -> {             JOptionPane.showMessageDialog(                     null, String.format(html, 200, s));             JOptionPane.showMessageDialog(                     null, String.format(html, 300, s));         };         SwingUtilities.invokeLater(r);     } } 

enter image description hereenter image description here

like image 90
Andrew Thompson Avatar answered Sep 20 '22 04:09

Andrew Thompson


Should work if you wrap the text in <html>...</html>

UPDATE: You should probably set maximum size, too, then.

like image 32
MarianP Avatar answered Sep 23 '22 04:09

MarianP