下面的代码不会编译失败,但是在运行时它在第 20 行和第 41 行显示 java.lang.NullPointerException。另外我有点好奇什么是空指针异常,运行时会发生什么?
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();
}
}
最佳答案
您正在向以下方法传递 null
...
panel.add(toolbar1);
panel.add(toolbar2);
这是因为以下内容尚未初始化。
private JToolBar toolbar1;
private JToolBar toolbar2;
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.
初始化
JToolBar toolbar1 = new JToolBar(SwingConstants.HORIZONTAL);
JToolBar toolbar2 = new JToolBar(SwingConstants.VERTICAL);
关于java - 程序中出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3478736/