How to Start a Java MVC Application With a Swing G

2019-07-04 10:58发布

Let us assume we have a simple Java MVC Application with the classes Model, View and Controller. The View class directly inherits from JFrame. As in a classic MVC setup, the view has a reference to the model and the controller has a reference to the view and to the model. As I just learnt, all GUI-related stuff should be wrapped in a SwingUtilities.invokeLater or something similar. Now what is the right way to initialise/start this application? I think the creation of the model and the controller should not be inside of the EDT, right? So I would come up with something like this:

final Model model = new Model();
SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        final View view = new View(model);
        new Thread(new Runnable() {
            @Override
            public void run() {
                new Controller(model, view);
            }
        }).start();
    }
});

Is this the correct way and a good idea or are there better possibilities?

EDIT: As correctly stated by @trashgod, a related example is examined here. Then I extend my question: What is basically done there is the following:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        Model model = new Model();
        View view = new View(model);
        new Controller(model, view);
    }
});

But isn't it wrong to run the whole application in the EDT?

1条回答
混吃等死
2楼-- · 2019-07-04 11:26

All the code that creates or interacts with Swing components must run on the event dispatch thread. So the second form of your code, that is the bellow code is correct.

`SwingUtilities.invokeLater(new Runnable() {
        @Override
    public void run() {
        Model model = new Model();
        View view = new View(model);
        new Controller(model, view);
    }
});`

The reason for all UI code that must run through EDT or worker thread is to avoid Multithreaded problem. You may see many swing programs may not init code in EDT. This is perfectly ok. But when your swing gets complecated, then there is probability for error. my self in simple swing apps lanching from main thread, i did not face dead locks are race conditions. Quick tasks uses EDT and long running tasks uses worker threads. Here is link on multithreaded problem on ui

Please let me know if i went wrong

查看更多
登录 后发表回答