Search code examples
javaswingjbuttonchessimageicon

Changing ImageIcon in a Java grid


I have a simple chess board which I'm trying to add pieces too. I want to change the icon image without adding more squares. How can I do this?

I just want to overwrite the image which is in that square, however what I have at the moment seems to add more squares.

The chess square class takes the piece type and x/y coordinates.

Code below:

Chess Board:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ChessBoard2
{   
    public static void main(String[] Args)
    {
        JFrame a = new JFrame("Chess");
        JPanel panel = new JPanel();
        ChessSquare[][] squares = new ChessSquare[8][8];
        panel.setLayout(new GridLayout(8,8));   

        int x = 0; 
        int y = 0;

        for ( x=0; x<8; x++)
            for( y=0; y<8; y++)
            {
                squares[x][y] = new ChessSquare("emptysquare", x, y); 
                panel.add(squares[x][y]);
            }

        x=5;y=8;
        squares[x][y] = new ChessSquare("king", x, y);

        a.setSize(375,375);
        a.setContentPane(panel);
        a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        a.setVisible(true);

    }
}

Chess Square:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ChessSquare extends JButton
{   
    private int xPosition;  
    private int yPosition;  
    private String filename;

    public ChessSquare(String type, int x, int y)
    {
        super();

        xPosition = x;
        yPosition = y;

       if (type == "emptysquare")
       { filename = "EmptySquare.jpg";}

       if (type == "king")
       { filename = "king.jpg";}

       ImageIcon square = new ImageIcon(filename);  
       setIcon(square);

    }
}

Thanks.


Solution

  •     x=5;y=8;
    

    You can't do that because you will get an Exception. Your array is 8x8, but it is 0 offset so you index the array using values 0-7.

        squares[x][y] = new ChessSquare("king", x, y);
    

    All that statement does is add a ChessSquare to your array. It doesn't add the ChessSquare to the panel.

    As you say you don't want to create a new ChessSquare anyway, you just want to change the Icon of an existing square. So the code should be something like:

    ChessSquare piece = squares[4][7];
    piece.setIcon( yourKingIcon );
    

    Your basic code for creating the ChessSquare is wrong. You should pass the Icon as a parameter. You should not be reading the icon in the ChessSquare class.