Can any one tell me what is the actual difference between this two codes as they both produce same result?
code1:
public class JLabelDemo extends JApplet {
public void init() {
this.setSize(400, 400);
ImageIcon ii = new ImageIcon("Flock_icon.png");
JLabel jl = new JLabel("<<--- Flock_icon", ii, JLabel.CENTER);
add(jl);
}
}
code2:
public class JLabelDemo extends JApplet {
private static final long serialVersionUID = 1L;
public void init() {
this.setSize(400, 400);
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
makeGUI();
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeGUI() {
ImageIcon ii = new ImageIcon("Flock_icon.png");
JLabel jl = new JLabel("<<--- Flock_icon", ii, JLabel.CENTER);
add(jl);
}
}
I really didn't find any difference between the outputs generated. But I cant understand the code.
So can anyone give me the real world example of invokeAndWait method??
For code1 the 2 allocations and the add are executed on whatever thread calls init(). If this is not the event dispatch thread, then there may be a problem, as the Swing documentation says that almost all use of Swing should be done on the event dispatch thread.
For code2, the calls to Swing are guaranteed to be done on the event dispatch thread. This is the correct way to do things. It is ugly and complicated and you don't understand it (yet), but it is the right way to do things if init() will be called on any thread other than the EDT.