Java JFrame paint()上的NullPointerException
我很难弄清楚为什么会抛出nullpointerexception。它并没有真正影响到我不认为的任何东西,至少因为所有的东西都被正确地画出来了,但我不喜欢错误消息 如您所见,paint将其称为.game.paintg2。为了尝试调试,this.game.print中的所有内容都已注释掉-该函数不执行任何操作,因此不应成为问题的一部分Java JFrame paint()上的NullPointerException,java,nullpointerexception,jframe,paint,repaint,Java,Nullpointerexception,Jframe,Paint,Repaint,我很难弄清楚为什么会抛出nullpointerexception。它并没有真正影响到我不认为的任何东西,至少因为所有的东西都被正确地画出来了,但我不喜欢错误消息 如您所见,paint将其称为.game.paintg2。为了尝试调试,this.game.print中的所有内容都已注释掉-该函数不执行任何操作,因此不应成为问题的一部分 public class Application extends JFrame { private Game game;///<stores the rule
public class Application extends JFrame {
private Game game;///<stores the rules for the game and facilitates interactions
public Application() throws RoyException {
this.game = new Game(this, 2);
}
// @Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
try{
this.game.paint(g2);
}catch(Exception e)
{
System.out.println("CAUGHT " + e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
Application app = new Application();
} catch (RoyException e) {
System.out.println("An error occurred while running the program: " + e.getMessage());
System.out.print("Stack trace: ");
e.getStackTrace();
}
}
显然,在设置可见性/大小之后再设置窗口的图标是个坏主意 移动这条线之后
this.app.setIconImage(new ImageIcon("mushy.jpg").getImage());
以前
this.app.setSize(this.maxX, this.maxY);
this.mmenu.setVisible(true);
app.setVisible(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setAlwaysOnTop(true);
nullpointerexception抛出已停止。经验教训:首先设置窗口图标。在源代码中插入第153行?谢谢,忘记了那个应用程序。java:153就是这个。game.paintg2;第一,不要覆盖顶层容器的绘制方法。改用JPanel或JComponent之类的工具,您将获得更好的性能。在所述组件中的第二个组件。第三,总是打电话给super.paintXxx。这些方法中有很多,如果没有很好的理由,你真的不应该绕过它们。这就是确切的代码吗?堆栈跟踪的输出还显示“Game Creates”,表示另一个线程也运行代码。应用程序似乎是在构建完所有内容之前重新绘制的。你应该在EDT线程中创建GUI组件。谢谢,我在下面给出了答案。什么是EDT?
this.app.setSize(this.maxX, this.maxY);
this.mmenu.setVisible(true);
app.setVisible(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setAlwaysOnTop(true);