0

Estou tentando compilar um jogo da memória em java, mas dá o seguinte erro:

Exception in thread "main" java.lang.NullPointerException

at javax.swing.ImageIcon.<init>(ImageIcon.java:217)

at memorygame.Game.initSquares(Game.java:37)

at memorygame.Game.<init>(Game.java:24)

at memorygame.Main.<init>(Main.java:21)

at memorygame.Main.main(Main.java:33)

Veriquei essas linhas com o debug e não identifiquei o erro, abaixo a classe game e main, se necessário posto as outras. Classe Game

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Queue;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import utils.Generate;

public class Game extends JPanel implements Valida {
    private static final long serialVersionUID = 1L;
    private Square[][] squares;
    private LogicaGame logic;

    public Game() {
        setSize(400, 405);
        squares = new Square[4][4];
        logic = new LogicaGame(this, squares);
        addMouseListener(logic);
        initSquares();

    }


    private void initSquares() {
        Queue<Integer> generate = Generate.randomSequence(8);
        Generate.randomSequence(generate, 8);
        int pos = 0;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                Square s = new Square();
                pos = generate.remove();
                ImageIcon ii = new ImageIcon(this.getClass().getResource(
                        "images/" + pos + ".png"));
                s.setImage(ii.getImage());
                s.setPos(pos);
                s.setX(j * 100);
                s.setY(i * 100);
                s.setMyX(i);
                s.setMyY(j);
                squares[i][j] = s;
            }
        }
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(new Color(0, 0, 0));

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                Square s = squares[i][j];
                g2.drawImage(s.getImage(), s.getX(), s.getY(), this);
            }
        }
    }

    @Override
    public boolean valida() {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if (!squares[i][j].isBlock()) {
                    return false;
                }
            }
        }
        return true;
    }

}

Classe Main

    import java.awt.Color;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;

    public class Main extends JFrame {
    private static final long serialVersionUID = 1L;
    private Game game;

    public Game getGame() {
        return game;
    }

    public void setGame(Game game) {
        this.game = game;
    }

    public Main() {
        game = new Game();
        add(game);
        setBackground(new Color(238, 238, 238));
        setSize(410, 430);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);
        setTitle(":D");
    }

    public static void main(String[] args) {
        final Main main = new Main();
        new Thread() {

            @Override
            public void run() {
                while (true) {
                    if (main.getGame().valida())
                        break;
                }
                JOptionPane.showMessageDialog(main, "Ganhou!");
                main.hide();
            }

        }.start();

    }

}

1 Resposta 1

1

Segundo o stacktrace que você postou, a exceção está ocorrendo no construtor de ImageIcon, no método initSquares:

ImageIcon ii = new ImageIcon(this.getClass().getResource("images/" + pos + ".png"));

Quando o método getResource não encontra um recurso, ele retorna nulo. O que provavelmente está causado o NullPointerException.

Desta forma certifique-se que o recurso indicado pela string "images/" + pos + ".png" existe.

2
  • 1
    Desta forma certifique-se que o recurso indicado pela string "images/" + pos + ".png" existe. - E que esteja no mesmo pacote que a classe que está o invocando também.
    – user28595
    9/12/2016 às 11:59
  • Obrigado, após colocar as images no mesmo pacote, pois estava em outro, deu certo.
    – ADR
    9/12/2016 às 19:18

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .