可能的重复:
Java 中的 SwingWorker
我有几个需要一起工作的类,但它们不是。
一方面,我有主要:
public class Main
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
//JFrame dummy for JDialog errors
modal = new JFrame();
new PrimaryErrorDialog("Title", "Message", e, false);
JFrame masterWindow = new JFrame();
masterWindow.setVisible();
}
}
}
}
它创建 PrimaryErrorDialog 类:
private JDialog dialog = this;
private JTextArea text;
private JPanel buttonContainer;
private JButton sendErrorReportT, sendErrorReportF;
public PrimaryErrorDialog(String title, String message,
final Exception error, final boolean exit)
{
super(Main.modal, title, true);
//JButton for sending error report
sendErrorReportT = new JButton("Send Error Report");
sendErrorReportT.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
dialog.dispose();
dialog = new JDialog(Main.modal, "Sending...", true);
Worker thread = new Worker(error);
thread.start();
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
dialog.add(progress);
dialog.pack();
dialog.setVisible(true);
}
});
//JButton for not sending error report
sendErrorReportF = new JButton("Don't send error report");
sendErrorReportF.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
dialog.dispose();
if (exit)
{
System.exit(0);
}
}
});
buttonContainer = new JPanel();
buttonContainer.add(sendErrorReportT);
buttonContainer.add(sendErrorReportF);
add(text);
add(buttonContainer);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void cleanUpAndContinue()
{
dialog.dispose();
dialog = new JDialog(Main.modal, "title", true);
dialog.add(/*Jbutton with listener that disposes this dialog*/)
dialog.setVisible(true);
}
它调用扩展 Thread 的 Worker 类:
public class Worker extends Thread
{
Exception e;
public Worker(Exception error)
{
e = error;
}
@Override
public void run()
{
//do something that takes time
PrimaryErrorDialog.cleanUpAndContinue();
}
它返回到 PrimaryErrorDialog,然后它必须通知用户任务已完成,然后终止该对话框。
然后我们回到创建 masterWindow 的 main 。
所有这些代码都在创建 masterWindow 之前执行,因为该段在发生错误时运行(如果 LAF 不存在,.proprties 文件丢失等)...
这就是我创建虚拟 JFrame 的原因,所以 JDialog 可以附加到它,我不想让它成为 JFrame。
这段代码也稍后在程序中执行,对于“真正的”运行时错误,一些类只是有一点不同的参数和/或构造函数。
但是,这不起作用,我已经以百万种方式尝试过,我尝试使用 SwingWorker,似乎没有做我想做的事。通常甚至没有到达电子邮件代码,或者程序不等待对话框被释放......
而我想要什么?
发生错误。弹出对话框告诉我发生了错误并询问我是否要发送错误报告。我说不 - 对话框关闭,如果错误是致命的,则关闭整个程序。我说是的 - 对话框关闭,新的对话框打开,进度条不确定,而带有堆栈跟踪的电子邮件正在后台发送。电子邮件被发送,带有进度条的对话框关闭,并打开一个新的对话框,告诉我我的错误报告已发送。我按下 ok 并关闭对话框,如果错误是致命的,则删除整个程序,否则,继续从 Main 类离开的地方。
注意:任何类都可能发生错误,它不仅仅来自 Main...