有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

线程“awteventque0”NullPointerException中的java异常

下面是问题产生的原因,下面是给出问题的代码

private void formMouseClicked(java.awt.event.MouseEvent evt) {                                  
      int x;``
      int y;
        if (check == true)
        {
         x = evt.getX();
         xcod1 = x;

         y = evt.getY();
         ycod1 = y;
         check = false;
        }
        else
        {
         x = evt.getX();
         xcod2 = x;

         y = evt.getY();
         ycod2 = y;
         check = true;
        }
        System.out.println(xcod1+"  "+xcod2+"  "+ycod1+"  "+ycod2);
}                        



    @SuppressWarnings("null")
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    Graphics g = null;``
    g.drawLine(xcod1, ycod1, xcod2, ycod2);

}

共 (1) 个答案

  1. # 1 楼答案

    图形g是null。不能取消对null对象的引用(例如通过访问字段或方法)。取消引用这样的null对象会抛出NullPointerException

    NullPointerException javadoc:

    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.

    另外,除非你真的知道自己在做什么,否则不要取消空警告。IDE/编译器是为了帮助您,而不是妨碍您