"Error or bug" java.lang.NullPointerException

"Error or bug" java.lang.NullPointerException

我正在尝试像往常一样创建我的 JFrame,但我不知道为什么会抛出 java.lang.NullpointerException。

我读到这是因为你没有分配一个值,或者 null 不能用作一个值,但我几乎可以肯定我的代码编写正确。

这里是:

import javax.swing.*;

public class Mathme extends JFrame {
    JFrame home;      
    JLabel title; 

    public Mathme(){
        home.setResizable(false);           !!!13!!!!   
        home.setLocationRelativeTo(null);            
        home.setVisible(true);
        home.setDefaultCloseOperation(EXIT_ON_CLOSE);
        home.setSize(600,500);
        home.setTitle("Pruebax1");
    }    

    public static void main(String[] args) {
        Mathme c = new Mathme(); !!!!23!!!
    }
}

它抛出的正是这个:

***Exception in thread "main" java.lang.NullPointerException
    at mathme.Mathme.<init>(Mathme.java:13)
    at mathme.Mathme.main(Mathme.java:23)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)***

我会把引用的行号放在那里。

您永远不会将 home 变量初始化为任何对象,因此如果您尝试从它调用方法,您将看到 NPE 是有道理的。

// this declares a variable but doesn't assign anything to it
JFrame home;  // home is not assigned and is currently null

而不是

// this both declares a variable and assigns an object reference to it.
JFrame home = new JFrame();

另外,为什么要 class 扩展 JFrame,然后尝试在 class 中创建另一个 JFrame?

关于 "beautiful" 代码——您需要学习 Java 的代码格式规则。您不应该随机缩进代码,而是单个块中的所有代码都应该缩进相同的量。

关于:

I read that it is because you didnt asign a value, or null cant be used as a value but WTF, I mean Im almost sure my code is written correctly.

这意味着您还不理解 "assign a value" 的含义,它与声明变量(见上文)不同,并且在 [= 的大多数介绍的第一页中都有很好的解释33=] 书。请注意,Swing GUI 编程是 Java 编程的一个相当高级的分支,在进入 GUI 编程之前,您最好先阅读一些基本的书籍教程。


这将是创建类似于您尝试创建的 GUI 的另一种方法:

import java.awt.Dimension;
import javax.swing.*;

@SuppressWarnings("serial")
public class MathmePanel  extends JPanel {
   private static final int PREF_W = 600;
   private static final int PREF_H = 500;

   public MathmePanel() {
      // create my GUI here
   }

   // set size in a flexible and safe way
   @Override
   public Dimension getPreferredSize() {
      Dimension superSize = super.getPreferredSize();
      if (isPreferredSizeSet()) {
         return superSize;
      }
      int prefW = Math.max(PREF_W, superSize.width);
      int prefH = Math.max(PREF_H, superSize.height);
      return new Dimension(prefW, prefH);
   }

   private static void createAndShowGui() {
      MathmePanel mainPanel = new MathmePanel();

      // create JFrame rather than override it
      JFrame frame = new JFrame("Pruebax1");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      // Start Swing GUI in a safe way on the Swing event thread
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}