Results 1 to 4 of 4
- 02-10-2012, 11:04 PM #1
Senior Member
- Join Date
- Nov 2011
- Location
- Turkey
- Posts
- 378
- Blog Entries
- 24
- Rep Power
- 2
Null Pointer Exception in a very Simple Action Listener. Why ?
I have a MainFrame class that extends JFrame and constructs itself and adds a Jbutton called rollDice.
Here is my Test Class:
and my Brain Class:Java Code:public class MyApplication { private MainFrame mainFrame; private Brain brain; MyApplication() { this.mainFrame = new MainFrame(); this.mainFrame.rollDice.addActionListener(new RollDiceListener()); } class RollDiceListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { System.out.println(brain.rollDie()); mainFrame.validate(); } } }
When I click the Roll Dice button I get:Java Code:public class Brain { Random randomNumberGenerator; public int rollDie() { randomNumberGenerator = new Random(); return (randomNumberGenerator.nextInt(6))+1; } }
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at myPaackkage.MyApplication$RollDiceListener.actionP erformed(MyApplication.java:24)
at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
Any help ?
- 02-10-2012, 11:26 PM #2
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,605
- Rep Power
- 5
Re: Null Pointer Exception in a very Simple Action Listener. Why ?
You need to create an instance of Brain in the MyApplication class.
...brain is never initialized.Java Code:private Brain brain;
- 02-10-2012, 11:28 PM #3
Senior Member
- Join Date
- Nov 2011
- Location
- Turkey
- Posts
- 378
- Blog Entries
- 24
- Rep Power
- 2
Re: Null Pointer Exception in a very Simple Action Listener. Why ?
Thanks.. So simple..
-
Re: Null Pointer Exception in a very Simple Action Listener. Why ?
The key learning point is not to simply fix the NPE, but to understand that if you study the variables on the line the NPE is thrown, you often can back-track to find out why one of them is null. Also, learn to use System.out.println(...) debugging statements.
Similar Threads
-
null pointer exception help
By captain_turkiye in forum New To JavaReplies: 17Last Post: 12-04-2011, 12:27 AM -
null pointer exception
By Herah in forum New To JavaReplies: 1Last Post: 12-01-2011, 08:44 AM -
Null pointer exception a
By TaxpayersMoney in forum New To JavaReplies: 5Last Post: 08-16-2011, 12:37 AM -
Null Pointer Exception HELP!?
By 2wyked in forum New To JavaReplies: 3Last Post: 04-04-2011, 01:41 AM -
Simple Action/Listener Help GUI
By aanders5 in forum New To JavaReplies: 24Last Post: 10-18-2010, 06:43 PM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks