I am trying to show text – “You pressed Button” when you pressed one of buttons.
I am getting an NullPointerException. I have initialized the buttons inside the constructor of the class and after initialization, I called the following method from main().
Here is the code:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class ButtonDemo implements ActionListener{
JLabel jlab;
ButtonDemo(){
JFrame jfrm = new JFrame("A Button Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jbtnUp = new JButton("Up");
JButton jbtnDown = new JButton("Down");
jbtnUp.addActionListener(this);
jbtnDown.addActionListener(this);
jfrm.add(jbtnUp);
jfrm.add(jbtnDown);
JLabel jlab = new JLabel("Press a button.");
jfrm.add(jlab);
jfrm.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Up"))
jlab.setText("You pressed Up.");
else
jlab.setText("You pressed Down.");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ButtonDemo();
}
});
}
}
What is the reason for this exception and how can I solve it?
Regards.
Your code is shadowing the variable jlab by re-declaring it in the constructor leaving the class field null. Don’t do that and your NPE will go away.
i.e., change this:
to this:
A key to solving NPE’s is to carefully inspect the line that is throwing the exception as one variable being used on that line is null. If you know that, you can usually then inspect the rest of your code and find the problem and solve it.