Fifth, create a GUI class with a main method. In this main method, create an anonymous class that implements the Runnable interface with a run method and use the javax.swing.SwingUtilities.invokeLater method to run that code on the event dispatch thread.
时间: 2023-11-28 07:48:58 浏览: 103
Sure, here's an example of how you could create a GUI class with a main method that runs code on the event dispatch thread:
```java
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MyGUI {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("My GUI");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
```
In this example, we create a JFrame with the title "My GUI", set its size to 400x300 pixels, set the default close operation to exit the application when the user closes the window, and make it visible. We wrap this code in an anonymous class that implements the Runnable interface and use the `invokeLater` method to run it on the event dispatch thread. This ensures that all GUI updates are done on the correct thread and avoids potential concurrency issues.
阅读全文