As I tried to see if I could answer this question earlier today. I realized that I don't fully understand the Event Dispatch Thread (EDT). Googling both confirmed and helped with that and clarified why I don't. (This might also be relevant to understanding.)
The code sets up a GUI and later (as in the earlier question) updates a text field until a flag is unset.
I have several questions/requests.
Please explain why the code below runs fine if both calls (to
swingInitanddoIt) are outside theinvokeLaterblock (as shown), since both calls affect or query the GUI yet neither are executing on the EDT (are they?). Isn't that inviting failure?Code also runs if call to
swingInitis inside anddoItoutsideinvokeLater. SoswingInitis executed on the EDT, but shouldn'tdoItnot executing on the EDT be a problem? (I was surprised that this worked. Should I have been?)I guess I understand why it hangs if
doItis insideinvokeLaterregardless of whereswingInitis: the purpose ofinvokeLateris ONLY to initialize the GUI (right?).Should
doItonly be initiated (possibly from an event occurring) on the EDT but certainly not insideinvokeLaterblock?
(The history of the EDT concept is interesting. It was not always thus. See link above to "why I don't" understand it.)
import static java.awt.EventQueue.invokeLater;
import java.awt.event.*;
import javax.swing.*;
public class Whatever
{
static boolean flag = true;
static JTextField tf = new JTextField("Hi",20);
static JPanel p = new JPanel();
static JFrame f = new JFrame();
static JButton b = new JButton("End");
public static void main(String[] args)
{
swingInit();
invokeLater
(
new Runnable()
{
@Override
public void run()
{
// swingInit();
// doIt();
}
}
);
doIt();
}
static void swingInit()
{
b.addMouseListener
(
new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
flag = false;
JOptionPane.showMessageDialog(null,"Clicked... exiting");
System.exit(0);
}
}
);
p.add(tf);
p.add(b);
f.add(p);
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
static String getInfo(){
return "Hello... " + Math.random();
}
static void doIt(){
while(flag)
tf.setText(getInfo());
};
}