SwingWorker中的错误处理 [英] Error handling in SwingWorker

查看:163
本文介绍了SwingWorker中的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是基于理论的问题,但它确实符合我的特定需求。

My question is a theory-based question, but it does meet a specific need I have.

你是什么?当你的SwingWorker抛出a)你可以预料到并且b)需要从中恢复并继续,但是你想通知用户这个错误发生了吗?你如何抓住预期的异常并通知用户没有违反没有Swing代码来自 doInBackground()规则?

What do you do when your SwingWorker throws an Exception that you a) can anticipate and b) need to recover from and continue, but you want to notify the user that this error has happened? How do you grab the expected exception and notify the user without violating the "No Swing code from doInBackground()" rule?

考虑到这一点,我有问题,制定了一个SSCCE,我想提出下面的问题。

I have, in consideration of this problem, developed a SSCCE that I would like to put forth with the questions below it.

SSCCE:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class Test {

    public static void main(String args[]) {
        final JFrame frame = new JFrame();
        JButton go = new JButton("Go.");
        go.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Task(frame);
            }
        });
        frame.add(go);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    static class Task extends SwingWorker<Void, Void> {
        JFrame parent;
        JDialog dialog;
        public Task(JFrame parent) {
            this.parent = parent;
            dialog = new JDialog(parent);
            JProgressBar jpb = new JProgressBar();
            jpb.setIndeterminate(true);
            dialog.add(jpb);
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
            execute();
        }

        @Override
        protected Void doInBackground() throws Exception {
            for(int i = 0; i < 100000; i++) {
                System.out.println(i);
                try {
                    if(i == 68456) throw new IllegalStateException("Yikes! i = 68456.");
                } catch (final IllegalStateException e) {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            JOptionPane.showMessageDialog(parent, "Error: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                }
            }
            return null;
        }

        @Override
        protected void done() {
            if (!isCancelled()) {
                try {
                    get();
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("done");
            dialog.dispose();
        }

    }
}

doInBackground()方法中调用 SwingUtilities.invokeAndWait()是否有效?我做了对此进行了一些线程分析,结果如下:

Is it valid to call SwingUtilities.invokeAndWait() within the doInBackground() method? I did some Thread profiling on this and the results were thus:

按下开始按钮后, SwingWorker-pool-1-thread-1 线程变为绿色。然后,当满足if条件时,抛出错误,并显示错误对话框,线程变为黄色,并且上确实存在绿色blip AWT-EventQueue-0 线程,表示已调用EDT。我等了大约10秒,按下确定, SwingWorker 线程再次变为绿色。

Once the "Go" button is pressed, the SwingWorker-pool-1-thread-1 thread goes Green. THEN, when the if condition is met, the error is thrown, and the error dialog is displayed, the thread goes yellow, and there is indeed a green "blip" on the AWT-EventQueue-0 thread, indicating that the EDT was invoked. I waited about 10 seconds, pressed "ok," and the SwingWorker thread went green again.

有没有做这样的事情有潜在的陷阱吗?有没有人有从 SwingWorker 实时通知用户计算错误的经验?

Are there any potential pitfalls to doing something like this? Does anyone have experience with notifying users of computation errors in real time from the SwingWorker?

我会诚实的,这种做法让我很谨慎。 似乎 非正统但我不能确定这是不是一个坏主意。

I'll be honest, this approach has me leery. It seems unorthodox but I cannot say for certain whether this is a bad idea.

推荐答案

当用户实际需要批准时,我发现使用 invokeAndWait()没有问题。如果没有,如示例所示, SwingWorker< Void,String> 可以简单地调用 publish(),并且数据和错误消息是交错的。在 done()中附加的合适消息将允许用户在必要时查看累积的输出。

I see no problem with using invokeAndWait() when the user actually needs to approve. If not, as shown in this example, a SwingWorker<Void, String> can simply call publish() with data and error messages interleaved. A suitable message appended in done() would allow the user to review the accumulated output if necessary.

这篇关于SwingWorker中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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