I am new to swing and still learning the ins and outs of it. I wrote a basic code and started experimenting with EDT. Here is the code:
public class SwingDemo2 extends Thread implements ActionListener {
JLabel jl;
SwingDemo2() {
JFrame jfr = new JFrame("Swing Event Handling");
jfr.setSize(250, 100);
jfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jl = new JLabel("Press a button!", SwingConstants.CENTER);
System.out.println("After Label: " + SwingUtilities.isEventDispatchThread());
JButton jb1 = new JButton("OK");
jb1.setActionCommand("OK");
jb1.addActionListener(this);
JButton jb2 = new JButton("Reset");
jb2.setActionCommand("Reset");
jb2.addActionListener(this);
jfr.add(jl, BorderLayout.NORTH);
jfr.add(jb1, BorderLayout.WEST);
jfr.add(jb2, BorderLayout.EAST);
System.out.println("After adding: " + SwingUtilities.isEventDispatchThread());
jfr.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("In main: " + SwingUtilities.isEventDispatchThread());
new SwingDemo2();
}
});
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand() == "OK") {
System.out.println("In OK: " + SwingUtilities.isEventDispatchThread());
jl.setText("You pressed Ok");
}
else if (ae.getActionCommand() == "Reset") {
System.out.println("In Reset: " + SwingUtilities.isEventDispatchThread());
jl.setText("You pressed Reset");
}
}
}
I added a few isEventDispatchThread()
methods to verify the thread I am in.
Apart from the GUI the messages in console were:
In main: true
After Label: true
After adding: true
In OK: true
In Reset: true
It seems all the time I was in the EDT. My question is, after the jfr.setVisible(true)
statement shouldn't the SwingDemo2()
constructor return to main()
and shouldn't that be the end of EDT?
I waited for many seconds before I first pressed any button in the GUI so why is still my event handling being done in EDT? Shouldn't that have given the EDT enough time to terminate?
Thanx in advance!