I’m working on an Applet, which has a JButton that I want to use to enable another JButton. However, when I press the button, I get the error: Exception in thread “AWT-EventQueue-1” java.lang.NullPointerException. Why is this happening? It seems as though when I run the Applet, the global variables don’t get instantiated (i.e. they are all “null”). In another program, everything works fine, and I can’t find any difference between the two in terms of implementing this action.
Here is a bit of my code:
public class implementation2 extends Applet implements ActionListener {
private static final long serialVersionUID = -4370650602318597069L;
...
public JButton coreButton, testButton;
...
public void init() {
...
final JButton testButton = new JButton("Test);
testButton.addActionListener(this);
...
final JButton coreButton = new JButton("CORE");
coreButton.addActionListener(this);
coreButton.setEnabled(false);
...
}
...
public void actionPerformed(final ActionEvent event) {
if(event.getActionCommand() == "Test") {
coreButton.setEnabled(false);
}
...
If anyone can point me in the direction towards fixing my code, that would be greatly appreciated! Thank you!
This is the problem:
Here you’ve created a local variable which shadows the instance variable for
testButton(and the same forcoreButton). That means the instance variables are still null – so when you try to dereference them later, you get an exception. You don’t want to declare new local variables ininit– you just want to assign the values to the instance variables. Corrected code: