来自助手 类 的 Swing 异常

Exceptions in Swing from helper classes

我正在做作业,将 this Java Knock Knock 应用程序教程转换为 Swing GUI 应用程序并使用多线程。

我有助手 class 抛出异常。这些 classes 不扩展 JFrame,我无法创建新的 JOptionPane 来显示异常。您将如何向用户显示该异常?

例如:我有一个 class 从两个文本文件(一个用于线索,一个用于答案)加载笑话。如果在我期望的位置找不到文本文件,我将抛出 NullPointerException。因为这是一个助手 class 它没有扩展 JFrame。我如何将该消息与用户相关联?我是否只引用 javax.swing.JOptionPane showMessageDialog 方法,就像我在下面的代码中那样,或者我可以有另一个代理 class 来捕获异常并显示它们?

    private final void getFilePath(ResponseFiles fileToGet) {
    String packagePath = "/com/knockknock/message";

    try {
    if (fileToGet == ResponseFiles.CLUES)
        file = new File(getClass().getResource(String.format("%s/clues.txt", packagePath)).getPath());
    else if (fileToGet == ResponseFiles.ANSWERS)
        file = new File(getClass().getResource(String.format("%s/answers.txt", packagePath)).getPath());
    } catch (NullPointerException e) {
        javax.swing.JOptionPane.showMessageDialog(null, "Jokes Files Missing", "File Missing", JOptionPane.ERROR_MESSAGE); 
    }

你怎么看?

您可以传递异常并单独处理,而不是在业务层使用 Swing 组件。

有一些自定义异常处理程序 class,您可以在其中处理 Runtime/Checked/Custom 异常。

public class ExceptionHandler {
    public void handleException(Exception exp) {
        if (exp instanceof NullPointerException) {
            javax.swing.JOptionPane.showMessageDialog(null,
                    "Jokes Files Missing", "File Missing",
                    JOptionPane.ERROR_MESSAGE);
        } else if (exp instanceof IOException) {
            javax.swing.JOptionPane.showMessageDialog(null, "Test", "Test",
                    JOptionPane.ERROR_MESSAGE);
        }
        //Handle other exceptions
    }
}

像这样改变你的方法

private final void getFilePath(ResponseFiles fileToGet) {
    String packagePath = "/com/knockknock/message";

    if (fileToGet == ResponseFiles.CLUES)
        file = new File(getClass().getResource(
                String.format("%s/clues.txt", packagePath)).getPath());
    else if (fileToGet == ResponseFiles.ANSWERS)
        file = new File(getClass().getResource(
                String.format("%s/answers.txt", packagePath)).getPath());
}

在完成 GUI 交互的业务层中,您可以像这样处理异常。在您的情况下,因为它是运行时异常,所以不需要显式抛出。

    try {
        getFilePath(ResponseFiles.CLUES);
    } catch (Exception e) {
        new ExceptionHandler().handleException(e);
    }