Hi, I recently decided to have another go at learning some programming, and decided to make some sort of 2d gameboard useable for stuff like Chess and Othello. I ran into a problem that I ran into last time I tried learning programming as well, and it has to do with updating Swing elements with a delay. Say I want to change the color or appearance of a series of JButtons, but I want to "turn" one button then wait for a second before turning the next one and so on. What I keep ending up with is that the program waits the combined waitingperiod for all the buttons then repaints them all at once. Last time I tried I went about the coding quite differently with classes extending Thread / implementing Runnable but always hit the same issue (Old "solutions" are on old computer which is currently not working) Here's todays attempt, if anyone is able to give me some pointers as to why it's updating in bulk instead of one by one I'd be very happy :) The main only contains new Board(8,8, "Game");
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Board implements ActionListener{
//GameButton[][] gameButtons;
JButton[][] gameButtons;
JFrame board;
public Board(int width, int height, String name) {
gameButtons = new JButton[width][height];
board = new JFrame(name);
board.setPreferredSize(new Dimension(height*60, width*60));
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
board.setVisible(true);
board.setLayout(new BorderLayout());
board.add(getButtons(width, height), BorderLayout.CENTER);
board.pack();
}
private JPanel getButtons(int width, int height) {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(width, height));
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
//gameButtons[i][j] = new GameButton(this, ""+i+""+j);
gameButtons[i][j] = new JButton();
gameButtons[i][j].addActionListener(this);
buttonPanel.add(gameButtons[i][j]);
}
}
return buttonPanel;
}
@Override
public void actionPerformed(ActionEvent arg0) {
swapColors();
}
private void swapColors() {
//gameButtons[3][1].changeColor(Color.WHITE);
gameButtons[3][1].setBackground(Color.WHITE);
System.out.println("a");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
gameButtons[3][2].setBackground(Color.WHITE);
gameButtons[3][2].repaint();
System.out.println("b");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
gameButtons[4][3].setBackground(Color.WHITE);
System.out.println("c");
}
}
EDIT:When changing from custom button (Extends JButton) to regular JButton for ease of reading I forgot to add actionListener in the post, that's fixed now.