关于java:JTextArea.setText不可见

JTextArea.setText not visible

我试图在Java中使用JTextArea.setText将某些内容显示在窗口上。 我想将屏幕尺寸设置为textarea,但是,两个.setText()之一未在屏幕上显示任何内容。

我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class SimpleFrame {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Demo");
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        double hi = d.getHeight();
        double wi = d.getWidth();
        JTextArea area = new JTextArea(10, 10);
        area.setEditable(false);
        area.setText("height:" + hi);
        area.setText("width:" + wi);
        frame.setSize(400, 400);
        frame.add(area);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }
}

输出:

1
width: 1920.0


您需要用area.append("...");附加文本,因为area.setText("...");会覆盖内容。

public void append(String str):
Appends the given text to the end of the document.

public void setText(String t):
Sets the text of this TextComponent to the specified text.