我试图像往常一样创建我的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是有意义的。
IE,
// 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的代码格式化规则。您不应该随机缩进代码,而应该将单个块中的所有代码缩进相同的数量。
关于:
我读到这是因为您没有分配值,或者不能将null用作值,但是WTF,我的意思是说我几乎可以确定我的代码编写正确。
这意味着您还不了解“赋值”与声明变量(参见上文)不同,并且在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();
}
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句