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

Throwing error (exception) in thread

我正在开发一个简单的 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");
    }
}

有可能,两个异常会同时抛出

当它出现时,我得到的是:

我有每个方法的线程 运行。我的问题是为什么程序会在这里停止工作。因为,当我分别启动这些线程之一时。它工作得很好。当我启动两个线程时,应该有 2 个错误 windows,但您可以看到空白错误 window 并且程序不工作。

我可以肯定地告诉您,根据您之前的评论,您遇到了 Swing 组件的 非线程安全 特性问题。您应该阅读 The Event Dispatch Thread 文档。您需要使用 invoke 方法来确保您的更改任务被放置在事件调度线程上,否则,是的,您的应用程序将崩溃。

代码示例:

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 实际在做什么:

Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI. In the following example the invokeLater call queues the Runnable object doHelloWorld on the event dispatching thread and then prints a message.