如何在JLabel中自动换文字?

Nad*_*eem 6 java swing jlabel

如何包装超过JLabel宽度的文字"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"?我已经尝试将文本包含在html标签中,但没有运气.请提出你的建议.

spl*_*bob 12

一种常见的方法是不使用a JLabel而是使用JTextArea带有自动换行和换行的方法.然后,您可以装饰JTextArea,使其看起来像JLabel(边框,背景颜色等).[根据DSquare的评论编辑包含完整性的换行符]

另一种方法是在标签中使用HTML,如此处所示.有警告

  1. 您可能必须处理HTML可能从纯文本解释/转换的某些字符

  2. myLabel.getText()现在调用将包含HTML(由于#1,可能包含转义和/或转换的字符)

编辑:以下是JTextArea方法的示例:

在此输入图像描述

import javax.swing.*;

public class JLabelLongTextDemo implements Runnable
{
  public static void main(String args[])
  {
    SwingUtilities.invokeLater(new JLabelLongTextDemo());
  }

  public void run()
  {
    JLabel label = new JLabel("Hello");

    String text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
//        String text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " + 
//                      "quick brown fox jumped over the lazy dog.";

    JTextArea textArea = new JTextArea(2, 20);
    textArea.setText(text);
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    textArea.setOpaque(false);
    textArea.setEditable(false);
    textArea.setFocusable(false);
    textArea.setBackground(UIManager.getColor("Label.background"));
    textArea.setFont(UIManager.getFont("Label.font"));
    textArea.setBorder(UIManager.getBorder("Label.border"));

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(label, BorderLayout.NORTH);
    frame.getContentPane().add(textArea, BorderLayout.CENTER);
    frame.setSize(100,200);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}
Run Code Online (Sandbox Code Playgroud)