Java Swing multi threads and ui freezes

孤者浪人 提交于 2019-12-01 09:07:25
trashgod

Download the file on a background thread and wrap just updateJlist() in a Runnable.

SwingWorker would be more reliable.

Addendum: As @mre notes, SwingWorker also makes it easy to report interim results, as shown here.

invokeLater does exactly the opposite of what you expect it to do - it runs operations on the EDT, which explains the behaviour.

I have create a WorkerThread class which take care of Threads and GUI current/main thread . i have put my GUI application in construct() method of WorkerThread when an event fire to start XXXServer then all threads are activate and GUI work smoothlly wihout freeze. have a look.

/** * Action Event * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */

public void actionPerformed(ActionEvent ae) { log.info("actionPerformed begin..." + ae.getActionCommand());

try {
    if (ae.getActionCommand().equals(btnStart.getText())) {
         final int portNumber = 9990;
         try {

             WorkerThread workerThread = new WorkerThread(){
                public Object construct(){

                    log.info("Initializing the Server GUI...");
                    // initializing the Server
                     try {
                        xxxServer = new XXXServer(portNumber);
                        xxxServer.start();
                        btnStart.setEnabled(false);                             
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        log.info("actionPerformed() Start button ERROR IOEXCEPTION..." + e.getMessage());
                        e.printStackTrace();
                    }
                    return null;
                }
            };workerThread.start();
            } catch (Exception e) {
                log.info("actionPerformed() Start button ERROR..." + e.getMessage());
                e.printStackTrace();
         }


    } else if (ae.getActionCommand().equals(btnStop.getText())) {
        log.info("Exit..." + btnStop.getText());
        closeWindow();
    }

} catch (Exception e) {
    log
        .info("Error in ServerGUI actionPerformed==="
            + e.getMessage());
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!