Java NullPointerException при использовании super.paintComponent (g);публично void paintComponent () {} - PullRequest
0 голосов
/ 27 сентября 2018

Я экспериментировал с графикой в ​​java, но когда я попытался запустить мой код, он выдал ошибку NullPointerException в строке с paintComponent(g); в нем.Я пытался установить 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)

Вот фактический код:

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

public class Game {
    public static void foodSpawn(int diff, int w, int h, Window W) {
        while(true) {
            W.newFood(new food(diff,w,h));
            try {TimeUnit.MILLISECONDS.sleep(20000);} catch (InterruptedException e) {e.printStackTrace();}
        }
    }
    public static void main(String[] args) {
        Random ran = new Random();
        int width = 300;
        int height =  300;
        int diff = 1;
        int squareS = 100;
        int x = width/2-squareS/2;
        int y = height/2-squareS/2;
        int velx = ran.nextInt(15)+1;
        int vely = ran.nextInt(15)+1;
        Enemy f = new Enemy(squareS);
        Window win = new Window(width,height,f);
        foodSpawn(diff,width,height,win);
        while(true) {
            if (x >= width-squareS || x<=0) {velx=-velx; diff++; velx++; x=x+velx;} else {x=x+velx;}
            if (y >= height-squareS || y<=0) {vely=-vely; diff++; vely++; y=y+vely;} else {y=y+vely;}
            f.newxy(x,y);
            width = Window.newW();
            height = Window.newH();
        }
    }
}
package com.arena.game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class Window extends JFrame{
    int x = 0;
    int y = 0;
    public static int getW;
    public static int getH;
    public void newFood(food f) {
        super.add(f);
    }
    public Window(int width,int height,Enemy f) {
        getW = width;
        getH = height;
        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        super.add(f);
        super.setSize(width, height);
        super.setVisible(true);
        super.getContentPane().addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent e) {
                Component c = (Component)e.getSource();
                int W = c.getWidth();
                int H = c.getHeight();
                getW = W;
                getH = H;
            }
        });
    }

    public static int newW() {
        return getW;
    }
    public static int newH() {
        return getH;
    }
}
package com.arena.game;
import java.awt.*;
import javax.swing.*;
import java.util.concurrent.TimeUnit;

public class Enemy extends JPanel{
    int x;
    int y;
    int SquareS;
    public Enemy(int SquareS) {
        this.SquareS = SquareS;

    }
    public void newxy(int x,int y) {
        this.x = x;
        this.y = y;
        try {TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
        paintComponent(this.getGraphics());
    }
    public void paintComponent(Graphics g) {
            super.paintComponent(g);
            this.setBackground(Color.BLUE);
            g.setColor(Color.RED);
            g.fillRect(x, y, SquareS, SquareS);
    }
}
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;
    public void paintComponent(Graphics g ,int Score) {
        super.paintComponent(g); // ERROR LINE
        g.setColor(Color.GREEN);
        g.fillRect(x, y, Score, Score);
    }
    public food(int Difficulty,int Wid,int Hei) {

        int 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();y 
        }
        paintComponent(this.getGraphics(),Score);
    }
}

Извините, я не мог просто дать небольшой фрагмент.(Я не знал, где на самом деле была проблема) Поскольку я все еще плохо знаком с Java и графикой Java и все еще привыкаю к ​​этому типу кода

1 Ответ

0 голосов
/ 25 октября 2018

Я переписал ваш класс еды, и теперь он работает.А для правильной 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();
    }
}
...