我有这种方法将在程序开始时运行:

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()在仍然是静态函数的同时显示弹出窗口?

最佳答案

是。几种不同的方式。首先,可以使用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);

10-06 03:47