Java's Swing Threading

前端 未结 3 894
星月不相逢
星月不相逢 2020-12-16 16:36

My understanding is that if I start up another thread to perform some actions, I would need to SwingUtilities.invokeAndWait or SwingUtilities.invokeLater<

相关标签:
3条回答
  • 2020-12-16 16:44

    In my opinion you should almost never use invokeAndWait(). If something is going to take awhile that will lock your UI.

    Use a SwingWorker for this kind of thing. Take a look at Improve Application Performance With SwingWorker in Java SE 6.

    0 讨论(0)
  • 2020-12-16 16:46

    I keep the simple Thread inside EventQueue.invokeLater(...) and that worked smoothly...

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run(){
    
            new Thread(new Runnable(){
                public void run(){
    
                    try{
                        EdgeProgress progress = EdgeProgress.getEdgeProgress();
                        System.out.println("now in traceProgressMonitor...");
                        while(true){
                            // here the swing update
                            if(monitor.getState() == ProgressMonitor.STATE_BUSY){
                                System.out.println(monitor.getPercentDone()/2);
                                progress.setProgress(monitor.getPercentDone()/2);
                            }else{
                                break;
                            }
                            Thread.sleep(5);
                        }
                    }catch(InterruptedException ie){}
    
                }
            }).start();
    
        }
    });
    
    0 讨论(0)
  • 2020-12-16 17:05

    You should consider using SwingWorker since it will not block the UI thread, whereas both SwingUtilities methods will execute on the EDT thread, thus blocking the UI.

    0 讨论(0)
提交回复
热议问题