为什么我得到这个NullPointerException? [英] Why am I getting this NullPointerException?
问题描述
我不知道。在使用新的Canvas()初始化Canvas之后,引用它会导致NullPointerException。文档告诉我这可能发生时,当画布不是启用,但我不知道它是什么意思被启用。我试图调试它包括while(!cvs.isEnabled());但程序刚刚挂起。
I can't figure this out. After initializing a Canvas with new Canvas(), referencing it results in a NullPointerException. The doc tells me this can occur when the Canvas is not "enabled", but I don't know what it means to be enabled. I tried to debug it by including while(! cvs.isEnabled()); but the program just hung. What are the conditions that could result in a Canvas not being enabled, and how do I fix them?
Exception in thread "main" java.lang.NullPointerException
at matt.io.ConsoleCanvas.<init>(ConsoleCanvas.java:72)
at matt.io.ConsoleCanvas.<init>(ConsoleCanvas.java:51)
at matt.io.ConsoleCanvas.main(ConsoleCanvas.java:32)
public class ConsoleCanvas extends JFrame
{
private static final Font DEFAULT_FONT = new Font("Monospaced", Font.PLAIN, 12);
public static void main(String[] args)
{
ConsoleCanvas me = new ConsoleCanvas(); //ConsoleCanvas.java:32
//Program has crashed by this point, so rest of main removed to be concise
}
protected JTextField in;
private Canvas cvs;
private int row;
private int col;
public ConsoleCanvas()
{
this("Console Pane", 80, 10); //ConsoleCanvas.java:51
}
public ConsoleCanvas(String title, int rows, int cols)
{
in = new JTextField();
in.setEditable(true);
in.setFont(DEFAULT_FONT);
in.setColumns(cols);
cvs = new Canvas();
cvs.setSize(in.getWidth(), in.getHeight() * rows);
cvs.setFont(DEFAULT_FONT);
row = 0;
col = cvs.getGraphics().getFontMetrics().getHeight(); //ConsoleCanvas.java:72
//Program crashes at this line, so I'll leave out the rest for brevity again
//I've isolated the null to the Graphics returned by cvs.getGraphics()
}
}
推荐答案
我没有使用swing相当一段时间,但尝试在调用get graphics之前将画布添加到Panel中(面板也应该具有某种形式的布局)。
您可以在这里找到一个有趣的教程: http://docs.oracle.com/ javase / tutorial / uiswing /
为了出现在屏幕上,每个GUI组件都必须是包含层次结构的一部分,包含层次结构是一个以顶层容器为根的组件树我会给你一个。所以我认为实例化canvas类是不够的。图形对象只有在将其添加到顶级容器后才会分配给它。
I didn't work with swing for quite some time, but try adding the canvas to a Panel before calling get graphics (the panel should also have some form of layout). You can find an interesting tutorial here : http://docs.oracle.com/javase/tutorial/uiswing/ "To appear onscreen, every GUI component must be part of a containment hierarchy. A containment hierarchy is a tree of components that has a top-level container as its root. We'll show you one in a bit." So I think that instantiating the canvas class is not enough. The graphics object is assigned to your canvas object only after you add it to a top-level container.
这篇关于为什么我得到这个NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!