假设我有一个非常长的行,我想在 JLabel
中显示.我该怎么做?
目前,较长的行是这样的:
我必须调整窗口大小才能看到完整的文本。
当文本几乎达到我的 JFrame
的宽度时,我怎样才能做到有换行符? ?
我不确定这里是否需要任何代码来让您回答这个问题,但仍然:
我的框架属性:
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(450, 400));
frame.setLocation(new Point(400, 300));
frame.setLayout(new BorderLayout());
我要修改的标签:
question = new JLabel("Question:");
question.setFont(new Font("Serif", Font.BOLD, 15));
question.setHorizontalAlignment(JLabel.CENTER);
编辑: 更多详情:
我正在从文件中读取行,然后显示它们。行的大小不固定,所以我不知道放在哪里<br>
在.
编辑 2:
我最终使用了 JTextArea
.
private JTextArea textAreaProperties(JTextArea textArea) {
textArea.setEditable(false);
textArea.setCursor(null);
textArea.setOpaque(false);
textArea.setFocusable(false);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
return textArea;
}
最佳答案
再举一个例子,说明使用正确的布局管理器,包裹在 HTML
标签中的文本将自动包裹到可用空间...
public class TestHTMLLabel {
public static void main(String[] args) {
new TestHTMLLabel();
}
public TestHTMLLabel() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
StringBuilder sb = new StringBuilder(64);
sb.append("<html>I have something to say, it's beter to burn out then to fade away.").
append(" This is a very long String to see if you can wrap with in").
append("the available space</html>");
JLabel label = new JLabel(sb.toString());
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(label);
frame.setSize(100, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
关于java - JLabel - 将较长的文本显示为多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14737810/