繁体   English   中英

为什么handleEvent()方法会引发运行时异常?

[英]Why does handleEvent() method throw a runtime exception?

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

请在此处查看完整的异常消息。 (谷歌文档)

下面是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    }

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

请提供用于创建/设置传递到handleEvent()方法中的Event对象的代码。

您可以使用调试器并逐步检查代码,查看变量的状态,轻松确定此类问题的原因。

NullPointerException被抛出在handleEvent()方法中。 由于异常不会以其他方式影响程序,因此我通过使用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的所有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM