在线程中抛出错误(异常)

时间:2016-05-14 10:36:05

标签: java multithreading exception joptionpane

我正在开发一个简单的Java应用程序。我有抛出异常的问题。

实际上,应该在线程中抛出异常。所以有些线程是这些例外:

public void setVyplata(Otec otec) {

    try {
        otec.setVyplata(Integer.parseInt(textField1.getText()));

    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE);
        otec.setVyplata(0);
        textField1.setText("0");
    }

}

public void setVyplata(Mama mama) {

    try {
        mama.setVyplata(Integer.parseInt(textField2.getText()));

    } catch (NumberFormatException e) {

        JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE);
        mama.setVyplata(0);
        textField2.setText("0");
    }
}

有可能,两个例外都将同时抛出。

如果确实如此,这就是我得到的:

empty error message.... and my application stop working. i must close it trough task manager.

我为每个方法运行了线程。我的问题是为什么程序会停止在这里工作。因为,当我分开启动其中一个线程时。它完美地运作。当我启动两个线程时,应该有2个错误窗口,但是你可以看到空白的错误窗口和程序无效。

1 个答案:

答案 0 :(得分:2)

我可以默认告诉您,根据您之前的评论,您遇到了摆动组件的非线程安全特征的问题。您应该阅读The Event Dispatch Thread文档。您需要使用调用方法来确保将更改任务放在事件派发线程上,否则,您的应用程序将崩溃。

代码示例:

public void setVyplata(Otec otec) {

    try {
        otec.setVyplata(Integer.parseInt(textField1.getText()));

    } catch (NumberFormatException e) {

        SwingUtilities.invokeLater(() -> {
            JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE);
            otec.setVyplata(0);
            textField1.setText("0");
        });

    }

}

public void setVyplata(Mama mama) {

    try {
        mama.setVyplata(Integer.parseInt(textField2.getText()));

    } catch (NumberFormatException e) {

        SwingUtilities.invokeLater(() -> {
            JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE);
            mama.setVyplata(0);
            textField2.setText("0");
        });
    }
}

如果查看SwingUtilities文档,您可以很好地解释invokeLater实际在做什么:

  

导致doRun.run()在AWT事件上异步执行   调度线程。这将在所有挂起的AWT事件发生后发生   已被处理。应用程序线程时应使用此方法   需要更新GUI。在以下示例中,调用invokeLater   在事件分派上对Runnable对象doHelloWorld进行排队   线程然后打印一条消息。