JTextArea没有出现在JFrame中 - Java

时间:2015-08-10 16:26:41

标签: java jframe jtextarea

我正在创建一个由全窗口(J)TextArea组成的简单GUI。我已经创建了一个JFrame窗口和一个JTextArea文本区域并设置了它们。另外,我创建了一些颜色和我想要用于文本区域的字体。

运行该类时,窗口会按预期弹出,但文本区域不存在。

我已将文本区域设置为可见,因此这不是问题。

代码:

import java.awt.Color;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class GUI {

    public static void main(String[] args) {

        //create and set up window
        JFrame window = new JFrame("Console");

        window.setSize(800, 500);
        window.setVisible(true);
        window.setLocationRelativeTo(null);

        //create fonts and colors
        Color gray = new Color(34, 34, 34);
        Color lightGray = new Color(207, 191, 173);
        Font consolas = new Font("Consolas", Font.PLAIN, 15);

        //create and set up text area
        JTextArea text = new JTextArea();

        text.setSize(800, 500);
        text.setVisible(true);

        //text area font and colors
        text.setBackground(gray);
        text.setForeground(lightGray);
        text.setFont(consolas);

        text.append("Text");

    }   
}

结果是一个名为'Console'的空白窗口。

如何修复JTextArea以显示?

1 个答案:

答案 0 :(得分:3)

您应该使用add- Method将JTextArea添加到JFrame window.add(text);

添加后,另一点使框架可见。最后一行window.setVisible(true);。因为有时候会有奇怪的套装。