java swing 启动,正确启动Java Swing桌面应用程序的方法

What is the proper way to start the application that needs 5-10 seconds to retrieve initial data from the database? This is what I got so far but I am not sure that there are no better ways. I would like that GUI and database access would be in different threads so that GUI building would occur concurrently with data retrieval.

public static void main(String[] args) {

final Controller controller = new Controller();

SwingUtilities.invokeLater(new Runnable() {

public void run() {

View frame = new View();

controller.setView(frame);

}

});

Model model = new Model();

controller.setModel(model);

controller.getInitialData();

}

解决方案

You're sort-of on the right track. Hopefully this will make things a little more clear...

Swing is not thread-safe. That being said, there are a couple things you can do. One option is to use SwingUtilities to post a Runnable task on the Event Dispatch Thread to be executed. This will enable you to retrieve data from the database and update the UI in a separate thread while respecting Swing's single-threaded model.

SwingUtilities.invokeLater(new Runnable(){

@Override

public void run(){

// update UI

}

});

Another option, since this is a long-running task, is to use SwingWorker to provide updates to the UI either when done, or while processing.

As you can see, both of these mechanisms (i.e. SwingUtilities and SwingWorker) enable you to dedicate such tasks to other threads while providing you with the ability to place the result (which normally translates into an action) on the EventQueue for later (and safe) execution. Regardless of which one you choose, it is important to remember that long-running tasks should never take place in the EDT. And thus, as I've come to discover, the most important feature of any well-designed GUI is responsiveness.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值