为什么我的Java GUI中没有显示任何内容?

时间:2022-09-10 20:03:47

I am currently working on a calculator. Right now, I am trying to gain experience with coding Java GUI, by making a simple program that makes a window with a text field. The code can compile without errors, but when I execute the program, the window appears, but without the text field. How do I make the text field visible? The code is shown as follows:

我目前正在研究计算器。现在,我正在尝试通过编写一个带有文本字段的窗口的简单程序来获得编写Java GUI的经验。代码可以编译而不会出错,但是当我执行程序时,会出现窗口,但没有文本字段。如何使文本字段可见?代码如下所示:

import javax.swing.*;
import java.awt.*;
public class Window {
    public static void main(String[] args) {
    JFrame Window = new JFrame("Window");
        Window.setSize(400,550);
    Window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel Panel = new JPanel (new FlowLayout());
    JTextField TextField = new JTextField("Type something here");
    Window.setVisible(true);
    }
}

3 个解决方案

#1


4  

You haven't added any of the components to your JFrame. You can add them like so:

您尚未向JFrame添加任何组件。您可以像这样添加它们:

Panel.add(TextField);
Window.add(Panel);
Window.setVisible(true);

Side note: You should stick to the Java naming conventions. Use camel case for variable names.

附注:您应该坚持Java命名约定。使用驼峰大小写变量名称。

#2


0  

You need to add them before making the frame visible.

您需要在使框架可见之前添加它们。

Panel.add(TextField);
Window.add(Panel);

#3


0  

You need to take the components that you have instantiated (e.g. the Panel and TextField) and add them to appropriate containers.

您需要获取已实例化的组件(例如Panel和TextField)并将它们添加到适当的容器中。

For example:

Panel.add(TextField);
Window.add(Panel);

If you have not done so already, I would highly recommend visiting http://docs.oracle.com/javase/tutorial/uiswing/index.html for more information on how to use the Swing library.

如果您还没有这样做,我强烈建议您访问http://docs.oracle.com/javase/tutorial/uiswing/index.html以获取有关如何使用Swing库的更多信息。

#1


4  

You haven't added any of the components to your JFrame. You can add them like so:

您尚未向JFrame添加任何组件。您可以像这样添加它们:

Panel.add(TextField);
Window.add(Panel);
Window.setVisible(true);

Side note: You should stick to the Java naming conventions. Use camel case for variable names.

附注:您应该坚持Java命名约定。使用驼峰大小写变量名称。

#2


0  

You need to add them before making the frame visible.

您需要在使框架可见之前添加它们。

Panel.add(TextField);
Window.add(Panel);

#3


0  

You need to take the components that you have instantiated (e.g. the Panel and TextField) and add them to appropriate containers.

您需要获取已实例化的组件(例如Panel和TextField)并将它们添加到适当的容器中。

For example:

Panel.add(TextField);
Window.add(Panel);

If you have not done so already, I would highly recommend visiting http://docs.oracle.com/javase/tutorial/uiswing/index.html for more information on how to use the Swing library.

如果您还没有这样做,我强烈建议您访问http://docs.oracle.com/javase/tutorial/uiswing/index.html以获取有关如何使用Swing库的更多信息。