Home > Java > javaTutorial > How to Enable Word Wrap in a JLabel?

How to Enable Word Wrap in a JLabel?

Susan Sarandon
Release: 2024-12-04 09:21:18
Original
674 people have browsed it

How to Enable Word Wrap in a JLabel?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template