I’m writing a simple Knight’s Tour program with a graphical display. I’ve already written it to work with the console, and now I’m trying to transfer that code over so that it works with swing. I’ve got a button whose Action Listener starts and operates the process. Here is the code:
askButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int[][] tour = getBoard(); // generates a matrix representing a successful knight's tour
int count = 0;
while (count < 64) {
count++;
Location loc = searchFor(count, tour); //gets the location of the int "count" inside the matrix "tour"
board.setVisible(false); //board contains a matrix of JPanels called "grid".
grid[loc.row()][loc.column()].add(new JLabel("" + count)); //adds JLabel to JPanel with the proper number
board.setVisible(true); //reset to visible to show changes
delay(1000); //wait 1000 milliseconds - one second - to allow user to view changes
}
}
});
So that is the code. I want each number to show up individually with one second intervals in between, but as it stands, the frame becomes blank for a while and suddenly displays the results with all the numbers showing, once finished. Could someone please help? Thank you.
Your
delaymethod blocks the Event Dispatch Thread, avoiding repaints of those components. Take a look at the Swing Concurrency Tutorial for more information on Swing and threads.A possible solution for your problem is the use of a Swing
Timerinstead of thedelaymethod