I have Ex1 below:
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);
}
My result is: On the event thread? : FALSE | I’m about to be realized: false
Other 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());
}
}
result is: I’m about to be realized: false | On the event thread? : TRUE
My question is why Ex1- componentAdded() run in Intial Thread, but Ex2- actionPerformed() run in EDT ?
Your very first line in the main method creates a new object of type JFrame. This creation starts a new thread (in reality it starts more than one thread) – a new thread that waits for event queue items. This can be a mouse click for example.
To answer your question: The main thread – which is really called “main” – is invoking your 10 lines of code of the main method. This should be finished in some milliseconds. After that the main thread is gone, not existend anymore.
But as I said before, the AWT/Swing library has internally created one (yes, more) thread that is basically an ininite loop checking for user input. And the actionPerformed method is invoked from this thread.
My suggestion for you:
Create a breakpoint in your first line of the main method.
Debug your program.
When the debugger stops at line one (before JFrame is created) go to your command line and start jconsole
go to tab threads
notice thread “main”
execute single line (new JFrame)
notice coexistence of thread “main” and thread(s) “AWT-*”
press play on debugger and “main” will be gone but AWTs will persist