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.
put all answers here together
1.don't call sleep(int)
, wait(int)
during code executed from AWT / Swing Listener , use
or
2.after add
/ remove
/ modify
already visible container is required to call
revalidate()
and repaint()
, thenafter setVisible()
3. setVisible
must be wrapped inside invokeLater
in code your nature
Your delay
method 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 Timer
instead of the delay
method
When you are in that while loop, repaint()
is never called. That would be why you don't see anything until the method ends.
First of all, try to call revalidate() and repaint() after you make some change on the GUI. Second, I also had a GUI project which is similar to yours as my CSE assisnment.
During the process, I find that the GUI is not update simultaneously as I wanted. I tried many ways of working it out. The final solution is that give up using add JLabels or JPanels on the board(JFrame), instead, using setIcon or setText to have a better communication with the frame. Well, this is just my personally experience. Hope could of help for your project.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.