且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swing线程中的MVC是否安全

更新时间:2023-01-13 18:01:41

This is too long for a comment...

First and this is unrelated to the rest of this answer: there are many different MVCs out there and the one you used in that piece of code you posted here is not the same as the one used in the article you linked to: http://www.oracle.com/technetwork/articles/javase/mvc-136693.html

The article correctly points out that it's just "A common MVC implementation" (one where the view registers a listener listening to model changes). Your implementation is a different type of MVC, where the controller registers a listener listening to model changes and then updates the view.

Not that there's anything wrong with that: there are a lot of different types of MVCs out there (*).

(Another little caveat... Your view is aware of your controller in your example, which is a bit weird: there are other ways to do what you're doing without needing to "feed" the controller to the view like you do with your setControl(...) inside your MVCView.)

But anyway... You're basically nearly always modifying the GUI from outside the EDT (which you shouldn't be doing):

public void setIconLabel(final Icon icon) {
   myLabel.setIcon(icon);
}

You can check it by adding this:

System.out.println("Are we on the EDT? " + SwingUtilities.isEventDispatchThread());

This is because you're eventually doing these updates from your SwingWorker thread (the SwingWorker thread is run outside the EDT: it's basically the point of a Swing worker).

I'd rather update the GUI from the EDT, doing something like this:

public void setIconLabel(final Icon icon) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            myLabel.setIcon(icon);
        }
    });
}