Null Pointer Exception in program
The Below code does not fail to compile but however at runtime it says java.lang.NullPointerException at Line at line number 20 and 41. Also i am little bit curious to know what is Null Pointer Exception, what happens at runtime ?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Tool
{
private JToolBar toolbar1;
private JToolBar toolbar2;
private JPanel panel;
public Tool()
{
JFrame frame= new JFrame();
panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
JButton one = new JButton("one");
JButton two = new JButton("two");
JButton three = new JButton("three");
JButton four = new JButton("four");
toolbar1 = new JToolBar();
toolbar2 = new JToolBar();
toolbar1.add(one);
toolbar1.add(two);
toolbar2.add(three);
toolbar2.add(four);
toolbar1.setAlignmentX(0);
toolbar2.setAlignmentX(0);
panel.add(toolbar1);
panel.add(toolbar2);
frame.add(panel,BorderLayout.NORTH);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(400,300);
frame.setTitle("ZOOP");
frame.setVisible(true);
}
public static void main (String args[])
{开发者_运维知识库
Tool zoop = new Tool();
}
}
You are passing a null
on the following methods....
panel.add(toolbar1);
panel.add(toolbar2);
It's because the following haven't been initialized.
private JToolBar toolbar1;
private JToolBar toolbar2;
Definition of NullPointerException
Thrown when an application attempts to use null in a case where an object is required. These include:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
Initialize it
JToolBar toolbar1 = new JToolBar(SwingConstants.HORIZONTAL);
JToolBar toolbar2 = new JToolBar(SwingConstants.VERTICAL);
You haven't actually allocated toolbar1
or toolbar2
. You need to do something like:
toolbar1 = new JToolBar ();
toolbar2 = new JToolBar ("other toolbar");
just like you did with:
JButton one = new JButton("one");
The reason you're getting the exception is because you're trying to dereference it and there's nothing there.
See here for the JToolBar docs.
Initialize toolbars
private JToolBar toolbar1;
private JToolBar toolbar2;
You try to add buttons to your toolbars before you've created them. The simplest solution:
private JToolBar toolbar1 = new JToolBar();
private JToolBar toolbar2 = new JToolBar();
You should never catch the NullPointerException, you should always write your program such that it does not happen. Apply necessary null checks for the conditions that are mentioned by "The Elite Gentlemen" :)
精彩评论