Here is my code:
public class GUI
{
JFrame frame;
JPanel squares[][];
public void movePiece(int oriX, int oriY, int destX, int destY)
{
squares[destY][destX] = squares[oriY][oriX];
squares[oriY][oriX] = null;
frame.setVisible(true);
}
/* Constructor credited to stackoverflow user ranzy
http://stackoverflow.com/questions/2535417/chess-board-in-java */
public GUI()
{
frame = new JFrame("Chess");
squares = new JPanel[8][8];
frame.setSize(500, 500);
frame.setLayout(new GridLayout(8, 8));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
squares[i][j] = new JPanel();
if ((i + j) % 2 == 0) {
squares[i][j].setBackground(Color.white);
} else {
squares[i][j].setBackground(Color.orange);
}
frame.add(squares[i][j]);
}
}
ImageIcon pawnW = new ImageIcon(getClass().getResource("pawnW.png"));
ImageIcon knightW = new ImageIcon(getClass().getResource("knightW.png"));
ImageIcon bishopW = new ImageIcon(getClass().getResource("bishopW.png"));
ImageIcon rookW = new ImageIcon(getClass().getResource("rookW.png"));
ImageIcon queenW = new ImageIcon(getClass().getResource("queenW.png"));
ImageIcon kingW = new ImageIcon(getClass().getResource("kingW.png"));
ImageIcon pawnB = new ImageIcon(getClass().getResource("pawnB.png"));
ImageIcon knightB = new ImageIcon(getClass().getResource("knightB.png"));
ImageIcon bishopB = new ImageIcon(getClass().getResource("bishopB.png"));
ImageIcon rookB = new ImageIcon(getClass().getResource("rookB.png"));
ImageIcon queenB = new ImageIcon(getClass().getResource("queenB.png"));
ImageIcon kingB = new ImageIcon(getClass().getResource("kingB.png"));
squares[0][0].add(new JLabel(rookB));
squares[0][1].add(new JLabel(knightB));
squares[0][2].add(new JLabel(bishopB));
squares[0][3].add(new JLabel(queenB));
squares[0][4].add(new JLabel(kingB));
squares[0][5].add(new JLabel(bishopB));
squares[0][6].add(new JLabel(knightB));
squares[0][7].add(new JLabel(rookB));
squares[7][0].add(new JLabel(rookW));
squares[7][1].add(new JLabel(knightW));
squares[7][2].add(new JLabel(bishopW));
squares[7][3].add(new JLabel(queenW));
squares[7][4].add(new JLabel(kingW));
squares[7][5].add(new JLabel(bishopW));
squares[7][6].add(new JLabel(knightW));
squares[7][7].add(new JLabel(rookW));
for (int i = 0; i < 8; i++)
{
squares[1][i].add(new JLabel(pawnB));
squares[6][i].add(new JLabel(pawnW));
}
frame.setVisible(true);
}
}
When a user moves a piece, I want the squares to be updated. I.e. destination square should now hold the origin squares jlabel. I have attempted to do that with my movePiece
method. But, this isn't creating the change I'm looking for. Am I required to use add/remove methods? Also - will it be necessary to call frame.setVisible(true)
any time I make an update to the board?