使用带有JFrame的静态方法

时间:2014-04-03 16:00:39

标签: java swing static popup jframe

我有这个方法,它将在我的程序开始时运行:

public static void checkIntegrity(){
        File propertiesFile = new File("config.properties");
        if (propertiesFile.exists()) {
            JOptionPane.showMessageDialog(rootPane, "File was found");
        } else {
            JOptionPane.showMessageDialog(rootPane, "File was not found");
        }
    }

它基本上检查config.properties文件是否丢失,并相应地显示弹出窗口。

这是我的main功能:

public static void main(String args[]) {  
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUI().setVisible(true);
                checkIntegrity();
            }
        });
    }

问题在于checkIntegrity()函数使用rootPane来显示弹出窗口以通知用户。 rootPane虽然是非静态成员,但却无法在checkIntegrity()中使用它。

有没有办法让checkIntegrity()显示弹出窗口,同时仍然是静态函数?

2 个答案:

答案 0 :(得分:1)

是。几种不同的方式。首先,您可以使用null代替rootPane

JOptionPane.showMessageDialog(null, "File was found");

你也可以传递rootPane函数:

GUI pane = new GUI().setVisible(true);
checkIntegrity(pane);

并相应地更改功能减速度:

public static void checkIntegrity(GUI rootPane){

你最终可以使rootPane成为一个静态变量(这就是我这样做的方式):

class theClass{
    static GUI rootPane;
    public static void main...

对于最后一个,您还必须设置rootPane

rootPane = new GUI().setVisible(true);

答案 1 :(得分:1)

JOptionPane.showMessageDialog(...)方法允许您将null作为第一个参数传递,因此您无需担心rootPane是否为静态。另一个选择是您可以使方法checkIntegrity()非静态。这意味着在您的main()方法中,您需要先创建rootPane的实例,然后调用checkIntegrity()方法,如下所示:

RootPane rootPane = new RootPane();
rootPane.checkIntegrity();