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 10:50:21 浏览: 119
Sure, here's an example of how to create a GUI class with a main method and use an anonymous class to implement the Runnable interface and run the 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() {
@Override
public void run() {
JFrame frame = new JFrame("My GUI");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add components to the frame
frame.setVisible(true);
}
});
}
}
```
In this example, we create a `JFrame` object and set its properties, such as size and title. We then add components to the frame (not shown in the code snippet). Finally, we make the frame visible.
Note that we use the `SwingUtilities.invokeLater()` method to run the code on the event dispatch thread, which is necessary for updating the user interface components safely.
阅读全文