我在下面有Ex1:
main(String args[]) {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Press Here");
ContainerListener container = new ContainerAdapter() {
public void componentAdded(final ContainerEvent e) {
System.out.println("On the event thread? : " +
EventQueue.isDispatchThread());
}
};
frame.getContentPane().addContainerListener(container);
frame.add(button, BorderLayout.CENTER);
frame.setSize(200, 200);
System.out.println("I'm about to be realized: " +
EventQueue.isDispatchThread());
frame.setVisible(true);
}
我的结果是:在事件线程上?: 错误 | 我即将意识到:假
其他Ex2:
public class GridBagLayoutTester
extends JPanel implements ActionListener{
public GridBagLayoutTester() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JButton button = new JButton("Testing");
// do something...
button.addActionListener(this);
add(button, gbc);
}
public void actionPerformed(ActionEvent e) {
System.out.println("On the event thread? : " +
EventQueue.isDispatchThread());
}
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("I'm about to be realized: " +
EventQueue.isDispatchThread());
}
}
结果是:我即将实现:假| 在事件线程上?: 真的
我的问题是为什么 Ex1-componentAdded() 在初始线程中运行,而 Ex2-actionPerformed() 在 EDT 中运行?