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
swingInit
anddoIt
) are outside theinvokeLater
block (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
swingInit
is inside anddoIt
outsideinvokeLater
. SoswingInit
is executed on the EDT, but shouldn'tdoIt
not 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
doIt
is insideinvokeLater
regardless of whereswingInit
is: the purpose ofinvokeLater
is ONLY to initialize the GUI (right?).Should
doIt
only be initiated (possibly from an event occurring) on the EDT but certainly not insideinvokeLater
block?
(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());
};
}