Question

I have this method which is going to run at the start of my program:

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");
        }
    }

It essentially checks if the config.properties file is missing or not and displays a popup accordingly.

This is my main function:

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

The problem with this is that the checkIntegrity() function uses rootPane to display the popup in order to inform the user. rootPane though is a non-static member so it is not possible to use it in checkIntegrity().

Is there a way to make checkIntegrity() show the popup while still being a static function?

Was it helpful?

Solution

Yes. A couple of different ways. First of all, you could use null instead of rootPane:

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

You could also pass the function rootPane:

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

and change the function deceleration accordingly:

public static void checkIntegrity(GUI rootPane){

You could finally make rootPane a static variable (this is the way I would do it):

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

For this last one, you also have to set rootPane:

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

OTHER TIPS

JOptionPane.showMessageDialog(...) method allows you to pass null as the first parameter, so you don't need to be concerned about whether or not rootPane is static. Another option is that you can make the method checkIntegrity() non-static. This would mean that in your main() method you will need to create an instance of rootPane first, then call the checkIntegrity() method, like so:

RootPane rootPane = new RootPane();
rootPane.checkIntegrity();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top