“Exception in thread ”AWT-EventQueue-0“ java.lang.

2020-04-19 06:42发布

问题:

I am making a calculator for an AP Computer Science Final. I built the GUI in Eclipse using Jigloo, and I quickly tried to learn about Action Listeners so you can hit the buttons to make numbers appear. The problems started occurring when I started enter the actual code to make calculations. I keep getting the following error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at NewJFrame.<init>(NewJFrame.java:82)
at NewJFrame$1.run(NewJFrame.java:73)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

I'm pretty new to Java, and I've never attempted a project like this before. I would love if you guys can help me fix this problem. Here is a link to my actual code, it won't fit in the code box for some reason: Link to code

回答1:

You button variables aren't assigned until you call initGUI(), which is at the bottom of your constructor. So, when you do this:

jButton3.addActionListener(new ListenToOne());

... Java sees this:

null.addActionListener(new ListenToOne());

... which is obviously a problem.