use*_*425 10 java swing jlabel jpanel
所以说我有一个很长的行,我想在一个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());
Run Code Online (Sandbox Code Playgroud)
我要修改的标签:
question = new JLabel("Question:");
question.setFont(new Font("Serif", Font.BOLD, 15));
question.setHorizontalAlignment(JLabel.CENTER);
Run Code Online (Sandbox Code Playgroud)
编辑:更多细节:
我正在从文件中读取行,然后显示它们.线条的大小不固定,所以我不知道放在哪里<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;
}
Run Code Online (Sandbox Code Playgroud)
Mad*_*mer 24
再举一个例子,显示使用正确的布局管理器,包含在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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
arc*_*rcy 10
使用HTML在Label中显示文本.
JLabel fancyLabel = new JLabel("<html>Punch Taskmaster</html>");
Run Code Online (Sandbox Code Playgroud)
(添加了Taskmaster建议示例)
小智 5
使用HTML格式化.效果很好.
import javax.swing.*;
import java.awt.*;
public class Test {
public static void main(String[] args) {
final 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());
final JLabel question = new JLabel("<html>Question:<br>What is love?<br>Baby don't hurt me<br>Don't hurt me<br>No more</html>");
question.setFont(new Font("Serif", Font.BOLD, 15));
question.setHorizontalAlignment(JLabel.CENTER);
frame.add(question);
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)