我读到所有构建 Swing 组件和处理事件的代码都必须由事件调度线程运行。我了解这是如何通过使用该SwingUtilities.invokeLater()
方法来完成的。考虑以下代码,其中 GUI 初始化是在main
方法本身中完成的
public class GridBagLayoutTester extends JPanel implements ActionListener {
public GridBagLayoutTester() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JButton button = new JButton("Testing");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
button.addActionListener(this);
add(button, gbc);
}
public void actionPerformed(ActionEvent e) {
System.out.println("event handler code");
}
public static void main(String[] args) {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(new GridBagLayoutTester(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.pack();
frame.setVisible(true);
System.out.println("Exiting");
}
}
这段代码如何完美运行?我们正在JFrame
主线程中构造和调用许多其他方法。我不明白 EDT 究竟在哪里出现(它正在执行什么代码?)。该类的构造函数GridBagLayoutTester
也从该main
方法中调用,这意味着 EDT 没有运行它。
简而言之
- EDT 什么时候开始?(如果在运行此代码时启动了 EDT,JVM 是否会与 main 方法一起启动 EDT?)
- 按钮的事件处理程序代码是否在 EDT 上运行?