天天看点

label里面的文字换行_如何在JLabel中自动换行文本?

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

另一种方法是在标签中使用HTML,如seen here.其中有警告

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

>调用myLabel.getText()现在将包含HTML(可能包含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);

}

}