java - 程序中出现空指针异常

标签 java nullpointerexception

下面的代码不会编译失败,但是在运行时它在第 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/

相关文章:

java - 为什么 Guava 的 MultiMap 的 size 方法返回(非)预期的结果?

java - 递归通用用法

java - 需要简单解释 "lock striping"如何与 ConcurrentHashMap 一起工作

java - 为什么我不能用我的类的实例创建新线程?

java - Android程序问题,NullPointerExc

java - Netty 4 有多稳定?

java - 使用级联保存父实体时如何获取子实体ID

java - Java 中的快速排序(比较)

java - 没有明显代码错误的空指针异常错误

java - 重写 JFrame.setBackground() 时遇到问题