How to Enable Word Wrap in a JLabel
Question:
Is there a "word wrap" property for JLabel? I want the text in my JLabel to automatically break to the next line when it reaches the edge of the screen, similar to the "Word Wrap" feature in Notepad.
Answer:
While JLabel does not have a built-in "word wrap" property, you can achieve this effect using HTML styles (CSS) to set the width of the label's body. This will determine the number of lines to render and consequently the preferred height of the label.
Implementation:
Here's an example that demonstrates how to set the width in CSS to enable word wrap in a JLabel:
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>
In this example:
The above is the detailed content of How to Enable Word Wrap in a JLabel?. For more information, please follow other related articles on the PHP Chinese website!