开发者

Proper way to start Java Swing desktop application

开发者 https://www.devze.com 2023-03-13 23:46 出处:网络
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 l

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 o开发者_开发技巧ccur 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

精彩评论

暂无评论...
验证码 换一张
取 消