Making a chess game in Java, I want to move the pieces

2.4k views Asked by At

So I have my images stored as ImageIcon's on JButtons. I want the user to click on the JButton of the piece they want to use and then click on another JButton to move it there, how would I do this?

I've tried using an actionListener to get the ImageIcon but its proving very complicated especially because I have an 2d array of JButton Images.

ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {

                System.out.println(actionEvent.getActionCommand());

            }
        };

        JButton[][] squares = new JButton[8][8];
        Border emptyBorder = BorderFactory.createEmptyBorder();

        for (int row = 0; row < squares.length; row++) {
            for (int col = 0; col < squares[row].length; col++) {

                JButton tempButton = new JButton();

                tempButton.setBorder(emptyBorder);
                tempButton.setSize(64, 64);


                squares[row][col] = tempButton;
                squares[row][col].addActionListener(actionListener);
                panel.add(squares[row][col]);

                squares[0][0].setIcon(new ImageIcon(BoardGUI.class.getResource("castle.png"), "castle"));



            }
        }
2

There are 2 answers

0
Adam Evans On BEST ANSWER

Try the following code. I don't know the exact code for working with ImageIcons on JButtons, but this gets the ideas across:

JButton pieceToMoveButton = null;   //variable that persists between actionPerformed calls

public void actionPerformed(ActionEvent actionEvent)
{
    JButton button = (JButton)actionEvent.getSource();

    if (pieceToMoveButton == null)    //if this button press is selecting the piece to move
    {
        //save the button used in piece selection for later use
        pieceToMoveButton = button;
    }
    else        //if this button press is selecting where to move
    {
        //move the image to the new button (the one just pressed)
        button.imageIcon = pieceToMoveButton.imageIcon
        pieceToMoveButton = null;    //makes the next button press a piece selection
    }
}
0
Magerick On

Not sure if this is what you are looking for but is one way of moving the position of a JButton to another: Now as an example pretend that there is already code declaring and initializing a JButton (JButton thatotherbutton = new JButton...etc.). Moving it to a certain location can be done as such:

Rectangle rect = thatotherbutton.getBounds();
xcoordinate = (int)rect.getX();
ycoordinate = (int)rect.getY();
chesspiecebutton.setBounds(xcoordinate, ycoordinate, xlengthofbutton, ylengthofbutton);

Use these coordinates to set the new bounds (in other words, the position) of your JButton upon clicking on another JButton.