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?
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.
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.
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 .
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); } }
Should work if you wrap the text in <html>...</html>
UPDATE: You should probably set maximum size, too, then.
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