Reputation: 6980
I am working on a Java application that was developed by some guy as part of a research project. Following is the main method:
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// Change the name of the application on a mac
System.setProperty("com.apple.mrj.application.apple.menu.about.name",
"XX");
// Use the top of the screen for the menu on a mac
if( System.getProperty( "mrj.version" ) != null ) {
System.setProperty( "apple.laf.useScreenMenuBar", "true" );
}
try {
// Use system look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println("Cannot use system's look and feel; using Java's default instead");
}
// Create a new instance of XX
XX.getInstance();
}
});
}
Now, I do not understand why was an event queue used instead of just using
public static void main(String[] args) {
//the MAC stuff!!
XX.getInstance(); //this line creates the UI and the event handlers
}
Is there any significance of using the EventQueue?
Upvotes: 1
Views: 729
Reputation: 205875
The properties should be set on the Initial Thread, and the GUI should then be scheduled for construction on the event dispatch thread. Alternative approaches are shown here.
public static void main(String[] args) {
// Change the name of the application on a mac
System.setProperty(
"com.apple.mrj.application.apple.menu.about.name", "XX");
// Use the top of the screen for the menu on a mac
if (System.getProperty("mrj.version") != null) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
// Create a new instance of XX
XX.getInstance();
}
});
}
Upvotes: 2
Reputation: 147164
Swing (and, if we were being honest, AWT) are thread-hostile. Like the vast majority of GUI libraries, it isn't thread-safe and doesn't make sense for it to be - microsynchronisation isn't realistic. Worse it uses effectively mutable statics (actually uses a bizarre AppContext
idea) to run work on the AWT Event Dispatch Thread (EDT). This can occur even when setting up the GUI before "realisation".
Probably it wont be a problem. Perhaps in some cases, perhaps after a JRE update, it'll give some problems. Perhaps it'll just be a caret out of place. The question is, do you want to even have to think about risking that, or just slap in the standard Java-style verbose boilerplate?
Upvotes: 2
Reputation: 29629
EventQueue.invokeLater()
will run that Runnable on the GUI thread (dispatch thread). You need to run updates to the GUI from the dispatch thread. From your code here though, I don't think you really need it, you will only need to use it when you are running in a background thread (e.g. In a callback from an event).
Upvotes: 2