【问题标题】:Why does handleEvent() method throw a runtime exception?为什么 handleEvent() 方法会抛出运行时异常?
【发布时间】:2016-06-15 01:45:10
【问题描述】:

我使用 java.awt.Frame 制作了一个 GUI 文件 I/O 应用程序。有两个标记为“ENTER”和“DONE”的按钮。输入按钮使程序将文本字段中的数据存储到文件中,而完成按钮使程序退出。点击“ENTER”按钮的事件由action()方法处理,而“DONE”按钮的事件由handleEvent()方法处理。该程序运行并完美地完成了这项工作,但问题是每当我单击一个按钮时,终端窗口就会出现在 GUI 框架后面,显示一个长的运行时异常消息。我将整个异常消息中的几行中的一行标识为指向 handleEvent() 方法中的一行(line:78)。

See the full exception message here.(谷歌文档)

以下是 handleEvent()action() 方法的定义。 请预测运行时异常的可能原因并帮助我解决它。谢谢。

64    public boolean action(Event event, Object o){
65        if(event.target instanceof Button){
66            if(event.arg.equals("ENTER")){
67                try{
68                    addRecord(); //calls the function to write data to the file
69                }
70                catch(Exception e){}
71            }            
72        }
73        return super.action(event,o);
74    }
...
...
76    public boolean handleEvent(Event e){
77        if(e.target instanceof Button){
78            if(e.arg.equals("DONE"))
79            System.exit(0); //exits the program
80        }
81        return super.handleEvent(e);
82    }
...
...
84    public static void main(String args[]){
85        new ClassName().prepareGUI(); //prepareGUI() setups the Frame
86    }

【问题讨论】:

    标签: java events button runtime-error


    【解决方案1】:

    根据堆栈跟踪,在第 78 行,'e' 或 'e.arg' 为空。

    请提供您在其中创建/设置传递给 handleEvent() 方法的 Event 对象的代码。

    您可以使用debugger 轻松确定此类问题的原因,并单步执行您的代码,查看变量的状态。

    【讨论】:

    • 我没有在程序中创建Event对象,所以没有这样的东西被传递给handleEvent()方法。我想这个方法及其参数的工作方式与 MouseEventListenerKeyEventListener 接口及其参数的方法相同。我输入的代码与我从中学习的书中的代码模式一致。我真的不知道 Event 对象为空。
    • 请贴出这个类的全部代码。我无法理解提供的 sn-ps。在 AWT 中,按钮事件通常由 ActionListener 和 ActionEvent 处理。方法签名称为 public void actionPerformed(ActionEvent e)。你在那里使用什么样的“事件”对象?
    • 您是否有可能使用 AWT 1.0 API?那东西太老了,甚至很难找到有关它的文档。你从哪里得到编译这些东西的JDK?您使用的是什么 Java 版本?
    【解决方案2】:

    NullPointerExceptionhandleEvent() 方法中被抛出。由于异常不会影响程序,因此我通过使用 try-catch 块来捕获并吞下异常来解决获取该消息的问题,如下面的代码所示:

    public boolean handleEvent(Event e){
        try{
            if(e.target instanceof Button){
                if(e.arg.equals("DONE"))
                    System.exit(0); //exits the program
            }
        }
        catch(NullPointerException npe){} //catching and swallowing
                                         //the NullPointerException
        return super.handleEvent(e);
    }
    

    因此,我没有在 Frame 后面打开带有该错误消息的终端窗口。感谢@AndreasVogl 提供的所有帮助。

    【讨论】:

    • 您好 Progyadeep Moulik,很高兴您能以这种方式解决问题。我只想礼貌地说,捕获异常而不记录它们是一种不好的做法(被认为是“反模式”),因为它会隐藏问题。用简单的“if (x != null) {...}”避免空指针比捕捉要好得多。见stackoverflow.com/questions/15146339/…
    • @AndreasVogl 是的,先生,我之前也被告知这是不好的做法。我当时只是找到了解决问题的方法。感谢您告诉我使用 if 语句的另一种方式。我现在就用它。 :)
    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多