使用super.paintComponent(g)时出现Java NullPointerException在public void paintComponent(){}

时间:2018-09-27 09:22:01

标签: java graphics nullpointerexception paintcomponent

我一直在用Java测试图形,但是当我尝试运行代码时,它在行中带有paintComponent(g);的情况下给了我NullPointerException错误。我试图在方法{{1}中设置Graphics g,并且创建了一个几乎相同但仍然无法正常工作的敌人脚本。我检查了互联网,但只有一个,他们使用了一个线程来完全更改此代码的结构。例外:

paintComponent

这是实际代码:

Exception in thread "main" java.lang.NullPointerException
    at java.desktop/javax.swing.JComponent.paintComponent(JComponent.java:800)
    at com.arena.game.food.paintComponent(food.java:12)
    at com.arena.game.food.<init>(food.java:27)
    at com.arena.game.Game.foodSpawn(Game.java:8)
    at com.arena.game.Game.main(Game.java:24)

抱歉,我不能只给出一个小片段。 (我不知道问题出在哪里)因为我还是Java和Java图形的新手,并且仍然习惯于这种类型的代码

1 个答案:

答案 0 :(得分:0)

我重写了您的Food课,现在可以了。而且对于正确的Java应该是Food,而不是food

package com.arena.game;
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class Food extends JPanel{
    Random ran = new Random();
    int x;
    int y;
    private int _score = 0;

    @Override
    public void paintComponent( Graphics g ) {
        super.paintComponent(g); // ERROR LINE
        g.setColor(Color.GREEN);
        g.fillRect(x, y, _score, _score);
    }

    public Food(int Difficulty,int Wid,int Hei) {

        _score = ran.nextInt(ran.nextInt(Difficulty)+1);
        x = ran.nextInt(Wid)+1;
        y = ran.nextInt(Hei)+1;
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace(); 
        }
        repaint();
    }
}