Graceful exception handling in Swing Worker

前端 未结 4 835
春和景丽
春和景丽 2020-12-08 20:47

I am using threading in application through Swing Worker class. It works fine, yet I have a bad feeling about showing an error message dialog in try-catch block. Can it pote

4条回答
  •  情话喂你
    2020-12-08 21:41

    One option is to use SwingUtilities.invokeLater(...) to post the action on the EDT

    SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run(){
            JOptionPane.showMessageDialog(
                Utils.getActiveFrame(),
                msg, 
                "Error", 
                JOptionPane.ERROR_MESSAGE,
                errorIcon);
        }
    });
    

    And as you noted, SwingWorker is capable of reporting intermediate results, but you'll need to override process(...), which is called when you invoke publish(...).

    Regardless, why not just set a flag if an exception occurs, and if that flag is set, show the dialog in done() since it's executed safely in the EDT?

提交回复
热议问题