Skip to main content

SwingUtilities.invokeLater( Runnable ) method

1 reply [Last post]
ecrouse
Offline
Joined: 2007-01-29

Hi,

I have an application class with a JFrame member in it. In many GUI examples the JFrame itself is used as the "main" class so-to-speak and I wanted to further abstract by having an Application class which has a JFrame member in it, e.g.,

public class Application {

private static final JFrame appFrame;

public static void main( String[] args ) {

SwingUtilities.invokeLater( new Runnable() {
public void run() {
new JFrame().setVisible();
}
});
}

}

The problem I'm having is accessing and setting the appFrame member variable in the application class. This is as close as I have gotten but an error remains in the return statement of the static member function createGUI.

public class Application {

private static final JFrame appGUI = createGUI();

public Application() {
}

public static JFrame createGUI() {

Runnable guiThread = new Runnable () {
JFrame gui;
public void run() {
gui = new JFrame();
gui.setVisible( true );
}
public JFrame getGUI() {
return gui;
}
};

SwingUtilities.invokeLater( guiThread );

return guiThread.getGUI(); //Error: Cannot find symbol { method getGUI() }

}

public static void main( String[] args ) {
}

}

Thanks for any help. If anyone could suggest a complete better approach, by all means. The reason I want to do this is so that I can I the main application frame available to all parts of my program as a static instance so that I need not pass in the the JFrame as an argument into all the methods the may need to access the data from the GUI components. Sorry about the lack of proper indentation within the code.

Thanks a million,

EVAC

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
walterln
Offline
Joined: 2007-04-17

You can use [ code ] coder here [ /code ] tags without spaces to post code.

Creating a static variable isn't a great idea. If you need to get the top level window, you can use SwingUtilities.getWindowAnchester(Component).

The problem with your posted code is that you create a new frame and don't use the the appFrame variable.
[code]
public class Application {

private JFrame appFrame;

private void createGUI() {
appFrame = new JFrame("Application name");
// init frame content
appFrame.pack();
appFrame.setLocationRelativeTo(null);
appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
appFrame.setVisible(true);
}

public static void main( String[] args ) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
Application app = new Application();
app.createGUI();
}
});
}
}
[/code]