Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invokeAndWait Java [duplicate]

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??


2 Answers

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.

like image 145
Theodore Norvell Avatar answered Aug 09 '26 22:08

Theodore Norvell


invokeAndWait means that it will execute that code block in a separate thread and so won't block the main thread whilst it executes. It is used to create Swing GUI's.

like image 20
maloney Avatar answered Aug 09 '26 22:08

maloney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!