Tutorial :NullPointerException when running multiple Action events



Question:

Purpose of the code : Create two Buttons(button1 and button2). When User clicks button1, change the text of button2. When User clicks button2, change the text of button1.

Here's the code I'm using :

import javax.swing.*;  import java.awt.*;  import java.awt.event.*;    public class multiAL {  JButton button1;  JButton button2;  JFrame frame;  public static void main(String[] args) {      multiAL setterAL = new multiAL();      setterAL.go();  }    public void go() {      button1 =  new JButton("Click me, I'm One");      button2 =  new JButton("Click me, I'm Two");      frame.setSize(500,500);      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      frame.getContentPane().add(BorderLayout.WEST, button1);      frame.getContentPane().add(BorderLayout.EAST, button2);      frame.setVisible(true);      button1.addActionListener(new b1L());      button2.addActionListener(new b2L());  }    class b1L implements ActionListener {      public void actionPerformed(ActionEvent event) {          button2.setText("What??, you clicked 1??");      }  }    class b2L implements ActionListener {      public void actionPerformed(ActionEvent event) {          button1.setText("What??, you clicked 2??");      }    }  }  

It compiles perfectly, but when I run it I receive following error : Exception in thread "main" java.lang.NullPointerException at multiAL.go(multiAL.java:17) at multiAL.main(multiAL.java:11)

Till now, I've encountered only compile-time errors. So there are two question which I want to ask:

1) What's wrong with the code? 2) How to track down runtime errors?


Solution:1

frame is not initialized, so it resolves to null and you can't call methods on null objects. Like you initialized button1 and button2 you should also initialize frame.

frame = new JFrame();  


Solution:2

I believe your frame object is null. It is never initialized. You can read the runtime exception. It says multiAL.java:17

This means that in line 17 you get your NullpointerException


Solution:3

But where is the

frame = new JFrame();  

line of code ? Since frame is null, nothing can happen, I guess ...


Solution:4

Initialize frame before first using:

frame = new JFrame();  


Solution:5

Consider renaming your class to follow Java class name conventions: CamelCase (http://en.wikipedia.org/wiki/CamelCase)

And for the problem, as pointed by other users, is the frame object not being initialized.

Add the following line BEFORE the first use of the frame object:

frame = new JFrame();  frame.setSize(500,500);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »