正确启动Java Swing桌面应用程序的方法 [英] Proper way to start Java Swing desktop application

查看:681
本文介绍了正确启动Java Swing桌面应用程序的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启动需要5-10秒从数据库中检索初始数据的应用程序的正确方法是什么?这是我到目前为止所得到的,但我不确定没有更好的方法。我希望GUI和数据库访问将在不同的线程中,以便GUI构建将与数据检索同时发生。

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不是线程安全的。话虽这么说,你可以做几件事。一种选择是使用 SwingUtilities 在要执行的事件调度线程上发布 Runnable 任务。这将使您能够从数据库中检索数据并在单独的线程中更新UI,同时遵循Swing的单线程模型。

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
    } 
});

另一个选项,因为这是一个长期运行的任务,是使用 SwingWorker 到在完成或处理时提供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.

如您所见,这两种机制(即 SwingUtilities SwingWorker )使您能够将此类任务专用于其他线程,同时使您能够在 EventQueue 上放置结果(通常转换为操作)以后(和安全)执行。无论您选择哪一个,重要的是要记住长时间运行的任务不应该在 EDT 中进行。因此,正如我发现的那样,任何精心设计的GUI的最重要特征是响应性

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.

这篇关于正确启动Java Swing桌面应用程序的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆