gpt4 book ai didi

java - 如何使用整个 Jlabel 来保存文本

转载 作者:行者123 更新时间:2023-12-02 11:41:56 26 4
gpt4 key购买 nike

我想知道是否有一种方法可以使用 JLabels 的整个区域来显示文本,每当我使用 JLabel 时,即使文本量超过了 JLabel 的大小,所有文本都位于中心。有没有办法告诉 JLabel 中的文本使用整个 Jlabel?

最佳答案

你可以...

使用html中的文字换行并将其设置为标签,它会自动换行到容器的约束

Wrapped Label

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

你可以...

使用不可编辑的JTextArea,它支持开箱即用的换行/文字换行

Multi line, non editable textarea

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

public TestPane() {
StringBuilder sb = new StringBuilder(64);
sb.append("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");
setLayout(new BorderLayout());
JTextArea ta = new JTextArea(10, 20);
ta.setOpaque(false);
ta.setEditable(false);
ta.setBorder(null);
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
ta.setText(sb.toString());
add(ta);
}

}

}

还请记住,布局管理器的选择将对输出产生很大影响。这两个示例都使用 BorderLayout,但您也可以使用 GridBagLayout,请注意

关于java - 如何使用整个 Jlabel 来保存文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48481118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com