问题
I'm creating a simple video poker program and right now I'm working on the action that's performed after the user has specified the cards he wants to hold, and replace the discarded cards with new cards after the draw. I have an Action where I want to replace the cards one by one with a delay between all replacements, but with the code I have below, it'll sleep for 500 ms multiplied by the number of cards I have to replace and THEN replace all the cards at once, rather than replace it one at a time as I want. Any help is greatly appreciated!
Action drawAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
int deckPos = 5;
if((holdValFirst.getText()).equals("HELD")){}
else{
holdFirst.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
try
{
Thread.sleep(500);
}catch (InterruptedException ie){
System.out.println(ie.getMessage());
}
}
if((holdValSecond.getText()).equals("HELD")){}
else{
holdSecond.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
try
{
Thread.sleep(500);
}catch (InterruptedException ie){
System.out.println(ie.getMessage());
}
}
if((holdValThird.getText()).equals("HELD")){}
else{
holdThird.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
try
{
Thread.sleep(500);
}catch (InterruptedException ie){
System.out.println(ie.getMessage());
}
}
if((holdValFourth.getText()).equals("HELD")){}
else{
holdFourth.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
try
{
Thread.sleep(500);
}catch (InterruptedException ie){
System.out.println(ie.getMessage());
}
}
if((holdValFifth.getText()).equals("HELD")){}
else{
holdFifth.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
}
}
};
回答1:
When you sleep inside the event dispatch thread (EDT), the GUI is frozen. Every long running task should be done outside of the EDT, and all swing manipulations should be done in the EDT.
You should use a SwingWorker
to sleep in another thread, and publish some progress every 500ms. Or you could use a javax.swing.Timer
which would fire an event every 500ms.
来源:https://stackoverflow.com/questions/6670395/problems-with-my-thread-sleep