Im trying to make a chess game in a JFrame. I have a problem whem i'm rendering the pieces using drawImage.

This is a part of the code for each piece

private Image img;
private int x, y;
public Tura(int x, int y)
{
    this.x = x;
    this.y = y;
    this.img = new ImageIcon("C:/Users/Rares/Documents/PieseSah/cal.png").getImage();
}

And this is how i'm displaying:

for(int y=0;y<8;y++)
      for(int x=0;x<8;x++)
           g.drawImage(p[y][x].getImage(), 37+x*81, 62+y*81, this);

If i use the same image for each piece everything is OK. If i use the right image for each piece i get NullPointerException at the drawImage line.

population of p array:

   for(int y=0;y<8;y++)
            for(int x=0;x<8;x++)
            {
                if(y == 1 || y == 6)
                    p[y][x] = new Pion(x,y);
                else if(y == 0 || y == 7)
                    switch(x)
                    {   
                        case 0: case 7: p[y][x] = new Tura(x,y);break;
                        case 1: case 6: p[y][x] = new Cal(x,y);break;
                        case 2: case 5: p[y][x] = new Nebun(x,y);break;
                        case 3: p[y][x] = new Regina(x,y);break;
                        case 4: p[y][x] = new Rege(x,y);break;
                    }
                else p[y][x] = new PiesaBlank(x,y);
            }

This code is for my jframe

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tablasah;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Scanner;
import javax.swing.JFrame;

/**
 *
 * @author Rares
 */
public class Tabla extends JFrame {
    private PiesaSah[][] p = new PiesaSah[8][8];
    private Image dbImage;
    private Graphics dbg;
    public Tabla()
    {
        setTitle("Joc Sah");
        setSize(700,725);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initializare();
    }

    public void paint(Graphics g) {
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }

    public void paintComponent(Graphics g) {
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.DARK_GRAY);
        g.fillRect(27, 52, 648, 648);
        g.setColor(Color.LIGHT_GRAY);

        g.drawLine(27, 133, 675, 133);
        g.drawLine(27, 214, 675, 214);
        g.drawLine(27, 295, 675, 295);
        g.drawLine(27, 376, 675, 376);
        g.drawLine(27, 457, 675, 457);
        g.drawLine(27, 538, 675, 538);
        g.drawLine(27, 619, 675, 619);

        g.drawLine(108, 52, 108, 700);
        g.drawLine(189, 52, 189, 700);
        g.drawLine(270, 52, 270, 700);
        g.drawLine(351, 52, 351, 700);
        g.drawLine(432, 52, 432, 700);
        g.drawLine(513, 52, 513, 700);
        g.drawLine(594, 52, 594, 700);

        for(int y=0;y<8;y++)
            for(int x=0;x<8;x++)
                g.drawImage(p[y][x].getImage(), 37+x*81, 62+y*81, this);
    }
    public void initializare()
    {
        for(int y=0;y<8;y++)
            for(int x=0;x<8;x++)
            {
                if(y == 1 || y == 6)
                    p[y][x] = new Pion(x,y);
                else if(y == 0 || y == 7)
                    switch(x)
                    {   
                        case 0: case 7: p[y][x] = new Tura(x,y);break;
                        case 1: case 6: p[y][x] = new Cal(x,y);break;
                        case 2: case 5: p[y][x] = new Nebun(x,y);break;
                        case 3: p[y][x] = new Regina(x,y);break;
                        case 4: p[y][x] = new Rege(x,y);break;
                    }
                else p[y][x] = new PiesaBlank(x,y);
            }
    }
    public PiesaSah[][] getPiesaSah()
    {
        return p;
    }
    public void afisareTabla()
    {   
        System.out.println("\n------------------------------------------\nAfisez:");
        for(int y=7;y>=-1;y--)
        {
            if(y==-1)
                System.out.print("          y/x");
            else
                System.out.print("           " + y + " ");
            for(int x=0;x<8;x++)
            {   
                if(y==-1)
                    System.out.print(" " + x);
                if(y>-1)
                    System.out.print(" " + p[y][x].getChar());
            }
            System.out.print("\n");
        }
        System.out.println("------------------------------------------");
    }
    public int mutarePiesa()
    {
        Scanner scanner = new Scanner(System.in);
        System.out.print("\nCe piesa vreti sa mutati?\nx=");
        int x = scanner.nextInt();
        System.out.print("y=");
        int y = scanner.nextInt();
        if (p[y][x].getChar() == '-') {
            System.out.println("\nError: Nu exista piesa la acea locatie.");
            return 0;
        } else {
            System.out.println("\nPiesa selectata: " + p[y][x].getType() + "[" + p[y][x].getPosX() + "][" + p[y][x].getPosY() + "]");
            System.out.print("\nLa ce locatie vreti sa o mutati?\nx=");
            int z = scanner.nextInt();
            System.out.print("y=");
            int w = scanner.nextInt();
            if (x == z && y == w) {
                System.out.println("\nError: Nu ai mutat piesa (aceeasi locatie).");
                return 0;
            } else if (p[w][z].getChar() != '-') {
                System.out.println("\nError: Exista deja o piesa pe acea locatie.");
                return 0;
            } else {
                if (p[y][x].verificareMutare(z, w) == 1) {
                    p[w][z] = p[y][x];
                    p[y][x] = new PiesaBlank(x, y);
                    System.out.println("\nMutare efectuata cu succes.");
                    this.afisareTabla();
                } else return 0;
            }
        }
        System.out.println("Continuam? Da=1/Nu=0");
        return scanner.nextInt();
    }
}

This is a sample code for my queen

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tablasah;

import java.awt.Image;
import javax.swing.ImageIcon;

/**
 *
 * @author Rares
 */
public class Regina implements PiesaSah {
    private final String type = "Regina";
    private final char c = 'r';
    private Image img;
    private int x, y;
    public Regina(int x, int y)
    {
        this.x = x;
        this.y = y;
        this.img = new ImageIcon("C:/Users/Rares/Documents/PieseSah/regina.png").getImage();
    }
    public char getChar()
    {
        return c;
    }
    public String getType()
    {
        return type;
    }
    public Image getImage()
    {
        return img;
    }
    public int getPosX()
    {
        return this.x;
    } 
    public int getPosY()
    {
        return this.y;
    }           
    public int verificareMutare(int x, int y)
    {
        if(y < 0 || x < 0 || y > 8 || x > 8)
        {    
            System.out.println("Error mutare " + this.getType());
            return 0;
        }
        else if ((x-this.x == y-this.y) || (this.x == x && ((y > this.y) || (y < this.y))) || (this.y == y && ((x > this.x) || (x < this.x))))
        {
            this.x = x;
            this.y = y;
            return 1;
        }
        else 
        {
            System.out.println("Error mutare " + this.getType());
            return 0;
        }
    }
}

And the interface for my pieces

 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tablasah;

import java.awt.Image;

/**
 *
 * @author Rares
 */
public interface PiesaSah {
    public int verificareMutare(int x, int y);  
    public int getPosX();
    public int getPosY();
    public Image getImage();
    public String getType();
    public char getChar();
}

The exception ->

   Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
   at tablasah.Tabla.paintComponent(Tabla.java:65)
at tablasah.Tabla.paint(Tabla.java:36)
at javax.swing.RepaintManager$3.run(RepaintManager.java:819)
at javax.swing.RepaintManager$3.run(RepaintManager.java:796)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:796)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:769)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:718)
at javax.swing.RepaintManager.access$1100(RepaintManager.java:62)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1677)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at     java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
有帮助吗?

解决方案

I fixed this by removing from the constructors of the pieces this part of code

this.img = new ImageIcon("C:/Users/Rares/Documents/PieseSah/cal.png").getImage();

and adding it to my getImage method

like

public Image getImage()
{
    this.img = new ImageIcon("C:/Users/Rares/Documents/PieseSah/cal.png").getImage();
    return img;
}

Isnt this odd? All of the constructors we're called..

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top