Question

So im quite new to MVC structure.And im really confused on where/when to add my Gui part on EDT. This is where im really confused:

public class ECPS_MVC {
    //edt?
    EcpsView view =new EcpsView();//shoud i put it on edt here?? SwingUtilities... etc
    //edt?

    EcpsModel model =new EcpsModel();
    EcpsController controler=new EcpsController(view,model);

}

I have seen question on how to start gui on edt when using mvc How to Start a Java MVC Application With a Swing GUI

And answer suprised me.Why shoud be Model on edt as well?Is that really correct??I dont think so.

So question1- When is the best time to put my Gui on edt.When i create View? question 2- Do i have to do updates from my controller like this?Each time? -

public void setIconLabel(final Icon icon) {
    SwingUtilities.invokeLater(new Runnable() {//with swingutil on each method where i work with gui?
        @Override
        public void run() {
            myLabel.setIcon(icon);
        }
    });
}

If you understand please point me right direction and if needed provide short example code.Thank you.

Was it helpful?

Solution

Anything that interacts or can change the UI in anyway MUST do so from within the context of the Event Dispatching Thread.

Swing, by design, is not thread safe. That is, there are no checks in the default libraries to make determinations about what thread the various models and components are been executed on, it is assumed the developer will already have made these determinations.

So question1- When is the best time to put my Gui on edt.When i create View?

Immediately. You have no way of knowing when a component may become realised (displayed on the screen and/or attached to a native peer)

question 2- Do i have to do updates from my controller like this?Each time? -

No, in fact, I'd be very worried if I found myself coding like this all time. Make the determination that the models and components MUST be executed within the context of the EDT and make whatever is interacting with these models and components meet these requirements.

This would mean, if you are loading data from a separate Thread, you would need to ensure that any time they update the model, they are synchronizing these updates to the EDT to ensure that if the model notifies the UI, it all occurs within the context of the EDT.

Don't make assumptions about the state of the model, statements like "I know..." will come back to haunt you, especially when some one else makes use of your API.

Unless you physically create the model yourself (outside the EDT) and guarantee it's isolation while it's being loaded, don't assume anything that is given to you isn't attached to the UI in some way.

An easier solution is to use a SwingWorker when you want to perform operations off the EDT, as it provides this synchronisation via it's publish/process/done methods

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top