I read that all the code which constructs Swing components and handles Events must be run by the Event Dispatch Thread. I understand how this is accomplished by using the SwingUtilities.invokeLater()
method. Consider the following code where the GUI initialization is done in the main
method itself
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");
}
}
How is it that this code works perfectly ? We are constructing JFrame
and calling a host of other methods in the main thread. I do not understand where exactly the EDT is coming into picture here (what code is it executing ?). The constructor of the GridBagLayoutTester
class is also being called from the main
method which means the EDT is not running it.
In short
- When is the EDT being started ? (does the JVM start the EDT along with the main method if at all the EDT is started while running this code ?)
- Does the event handler code for the button run on the EDT ?