How to Enable Word Wrap in a JLabel?
Dec 04, 2024 am 09:21 AMHow 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:
- width: %1spx sets the width of the JLabel in pixels.
- String.format(html, 200, s) and String.format(html, 300, s) create HTML strings with different widths.
- The two JOptionPane.showMessageDialog calls display two JLabels with different widths, showing how word wrap is enabled when the width is set.
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte

How does Java's classloading mechanism work, including different classloaders and their delegation models?

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?

Iceberg: The Future of Data Lake Tables

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed

Node.js 20: Key Performance Boosts and New Features

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?
