且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在JLabel中自动换行?

更新时间:2022-12-22 22:52:11

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

A common approach is to not use a JLabel and instead use a JTextArea with word-wrap and line-wrap turned on. You could then decorate the JTextArea to make it look like a JLabel (border, background color, etc.).

另一种方法是在标签中使用HTML,如在此处看到.注意事项

Another approach is to use HTML in your label, as seen here. The caveats there are

  1. 您可能需要照顾HTML可以从纯文本解释/转换的某些字符

  1. You may have to take care of certain characters that HTML may interpret/convert from plain text

调用myLabel.getText()现在将包含HTML(可能 #1

Calling myLabel.getText() will now contain HTML (with possibly escaped and/or converted characters due to #1

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

Here's an example for the JTextArea approach:

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);
  }
}