나는 이것을 이해할 수 없다. 새 Canvas()로 Canvas를 초기화 한 후이를 참조하면 NullPointerException이 발생합니다. 이 문서는 캔버스가 "활성화"되어 있지 않을 때 발생할 수 있다고 알려주지 만 활성화 할 수 있다는 것이 무엇인지 모릅니다. while (! cvs.isEnabled());을 포함 시켜서 디버깅하려고했습니다. 그러나 프로그램은 단지 매달렸다. Canvas가 활성화되지 않을 수있는 조건은 무엇이며 어떻게 수정할 수 있습니까?왜이 NullPointerException이 발생합니까?
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()
}
}
"cvs.getGraphics(). getFontMetrics(). getHeight();"에있는 getter 중 하나입니다. null을 반환합니다 –
격리되었습니다. 'Graphics graphics = cvs.getGraphics(); if (graphics == null) System.out.println ("graphics"); –
getGraphics를 사용하지 마십시오. 커스텀 페인팅을하고 싶다고 가정하면 (Swing에서) paintComponent를 오버라이드하는 것입니다. – kleopatra