java gui mvc,如何使用Swing GUI启动Java MVC应用程序

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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值