gpt4 book ai didi

java - "Error or bug"java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-02 04:46:28 24 4
gpt4 key购买 nike

我试图像往常一样创建我的 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();

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

关于“漂亮”的代码——您将需要学习 Java 的代码格式化规则。您不应该随机缩进代码,而应将单个 block 中的所有代码缩进相同的量。

关于:

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.

这意味着您还不了解“赋值”的含义,它与声明变量(见上文)不同,并且在大多数 Java 介绍书籍的第一页中都有很好的解释。请注意,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();
}
});
}
}

关于java - "Error or bug"java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29618230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com