4

我想要JLabel多行格式的文本,否则文本会太长。我们如何在 Java 中做到这一点?

4

5 回答 5

11

如果您不介意将标签文本包装在html标签中,JLabel 会在其容器的宽度太窄而无法容纳所有内容时自动换行。例如,尝试将此添加到 GUI,然后将 GUI 调整为太窄 - 它会换行:

new JLabel("<html>This is a really long line that I want to wrap around.</html>");
于 2009-09-04T04:45:02.457 回答
8

我建议创建自己的自定义组件,在包装时模拟 JLabel 样式:

import javax.swing.JTextArea;

public class TextNote extends JTextArea {
    public TextNote(String text) {
        super(text);
        setBackground(null);
        setEditable(false);
        setBorder(null);
        setLineWrap(true);
        setWrapStyleWord(true);
        setFocusable(false);
    }
}

然后你只需要打电话:

new TextNote("Here is multiline content.");

textNote.setRows(2)如果要pack()正确计算父组件的高度,请确保设置行数 ( )。

于 2011-04-28T09:48:46.650 回答
3

可以在 HTML中使用(基本)CSS 。

在此处输入图像描述 在此处输入图像描述

于 2011-04-28T10:16:18.840 回答
3

我建议使用 JTextArea 而不是 JLabel

在您的 JTextArea 上,您可以使用方法 .setWrapStyleWord(true) 更改单词末尾的行。

于 2009-09-04T04:26:13.750 回答
1

具有自动调整高度的多行标签。在标签中换行

private void wrapLabelText(JLabel label, String text) {
    FontMetrics fm = label.getFontMetrics(label.getFont());
    PlainDocument doc = new PlainDocument();
    Segment segment = new Segment();
    try {
        doc.insertString(0, text, null);
    } catch (BadLocationException e) {

    }

    StringBuffer sb = new StringBuffer("<html>");
    int noOfLine = 0;
    for (int i = 0; i < text.length();) {
        try {
            doc.getText(i, text.length() - i, segment);
        } catch (BadLocationException e) {
            throw new Error("Can't get line text");
        }
        int breakpoint = Utilities.getBreakLocation(segment, fm, 0, this.width - pointerSignWidth - insets.left - insets.right, null, 0);
        sb.append(text.substring(i, i + breakpoint));
        sb.append("<br/>");
        i += breakpoint;

        noOfLine++;
    }
    sb.append("</html>");
    label.setText(sb.toString());

    labelHeight = noOfLine * fm.getHeight();
    setSize();
}

谢谢,Jignesh Gothadiya

于 2013-05-21T04:55:35.100 回答