I'm making a chess game in Java. And because I'm a beginner at Swing, I ran into a problem right away. I made a two dimensional array of buttons for the chessboard tiles. The problem is when my first button is clicked I do not know how to refresh that button or the panel it is in.
Here is the code.
public class Table extends JFrame implements ActionListener{
public JButton[][]tile = new JButton[8][8];
JPanel gamePAN = new JPanel();
int size=8;
Tile[][] tileList = new Tile[8][8];
private final Color lightTileColor = Color.decode("#FFFACD");
private final Color darkTileColor = Color.decode("#593E1A");
public Table() {
this.setResizable(true);
this.setVisible(true);
this.setTitle("Chess");
initCompoments();
Toolkit tk = Toolkit.getDefaultToolkit();
int xsize = (int) tk.getScreenSize().getWidth();
int ysize = (int) tk.getScreenSize().getHeight();
this.setSize(xsize, ysize);
private void initCompoments() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
gamePAN.setLayout(new java.awt.GridLayout(8, 8, 0, 0));
getContentPane().add(gamePAN);
gamePAN.setBounds(550, 100, 800, 800);
pack();
}
private void initialize() {
//gamePAN = new JPanel();
//gamePAN.setLayout(new GridLayout(size,size));
for(int i=0;i<size;i++) {
for(int j=0; j<size;j++) {
if(i%2==0) {
if(j%2==0) {
tile[i][j] = new JButton();
tile[i[j].setBackground(lightTileColor)
tile[i[j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}else {
tile[i][j] = new JButton();
tile[i[j].setBackground(darkTileColor);
tile[i[j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}
}else {
if(j%2==0) {
tile[i][j] = new JButton();
tile[i[j].setBackground(darkTileColor);
tile[i][j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}else {
tile[i][j] = new JButton();
tile[i[j].setBackground(lightTileColor);
tile[i][j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}
}
}
}
@Override
public void actionPerformed(ActionEvent ae) {
for(int r=0;r<size;r++) {
for(int c=0;c<size;c++) {
if(ae.getSource()==tile[r][c]) {
if(tileList[r[c].getPiece()!=null) {
tileList[r][c].getPiece().kretanje(tile, tileList);
}
}
}
}