Multiline JLabels – Java

我希望JLabel文本采用多行格式,否则文本会太长。 我们怎样才能在Java中做到这一点?

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

 new JLabel("This is a really long line that I want to wrap around."); 

我建议创建自己的自定义组件,在包装时模拟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."); 

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

我建议使用JTextArea而不是JLabel

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

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

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

具有自动调节高度的MultiLine标签。 在Label中换行文本

 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(""); 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("
"); i += breakpoint; noOfLine++; } sb.append(""); label.setText(sb.toString()); labelHeight = noOfLine * fm.getHeight(); setSize(); }

谢谢,Jignesh Gothadiya