سؤال

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.

نصائح أخرى

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.

You won't see any differences in small swing applications. In bigger applications where a UI painting takes longer time and/or multiple threads are involved in the applications, there you can see the differences.

From javadoc

invokeAndWait causes doRun.run() to be executed synchronously on the AWT event dispatching thread. This call blocks until all pending AWT events have been processed and (then) doRun.run() returns. This method should be used when an application thread needs to update the GUI. It should'nt be called from the EventDispatchThread.

You can also check here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top