首页 > 解决方案 > 尽管代码中没有错误,但 JFrame 未显示

问题描述

我是使用 Java GUI 的新手,我从 oracle.com 上的 java 教程中逐字复制了 HelloWorldSwing.java。Eclipse 没有在我的代码中显示任何错误,当我运行它时,没有显示任何窗口,并且程序在一两秒后终止。

我使用的代码:

public class HelloWorldSwing {
/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("HelloWorldSwing");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add the ubiquitous "Hello World" label.
    JLabel label = new JLabel("Hello World");
    frame.getContentPane().add(label);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

}

任何帮助,将不胜感激。

标签: javaeclipseswing

解决方案


推荐阅读