像“aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... 我试过将文本包含在 html 标签中,但没有成功。 请提出您的建议。
最佳答案
一种常见的方法是不使用 JLabel
,而是使用启用了自动换行和换行的 JTextArea
。然后您可以装饰 JTextArea 使其看起来像 JLabel(边框、背景颜色等)。 [根据 DSquare 的评论进行了编辑以包括换行以确保完整性]
另一种方法是在标签中使用 HTML,如 seen here .有一些注意事项
您可能需要注意 HTML 可能从纯文本解释/转换的某些字符
调用
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);
}
}
关于java - 如何在 JLabel 中自动换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26420428/