I have a method here that creates 52 JButtons in a loop. When a button is clicked, according text is displayed on it. After two buttons' text has changed, the program sleeps for 1 seconds (to give the user time to look at them). However, the program sleeps before the button text change animation finishes and ends up not showing the text on the second button:
for(int i=0; i<52; i=i+1){
//button creation
final int a=i;
JButton button_one=new JButton();
buttons[a]=button_one;
mainpanel.add(button_one);
button_one.addActionListener(new ActionListener(){
// what happens when the button is clicked
@Override
public void actionPerformed(ActionEvent button_picked){
amount_of_cards_picked=amount_of_cards_picked+1;
cardamountcheck();
String selectedcard=null;
if(twocardspicked==true){
userpick2=a;
selectedcard=setoutcards[userpick2];
System.out.println(selectedcard);
// button shows name of card
buttons[a].setText(selectedcard);
pairdetermination();
pairprobability();
}
else if(twocardspicked==false){
userpick1=a;
selectedcard=setoutcards[userpick1];
System.out.println(selectedcard);
System.out.println(cardspritesmap.get(selectedcard));
buttons[a].setText(selectedcard);
// the two changed text buttons are stored in an array
}
if(twocardspicked==true){
pickedcardbuttons[1]=buttons[a];
}
else if(twocardspicked==false){
pickedcardbuttons[0]=buttons[a];
}
// sleep method is called
oncardflipped(selectedcard);
}
});
}
This is the method that starts the Thread.sleep():
public void oncardflipped(String card){
if(twocardspicked==true){
// if there are two cards picked, the sleep is activated
try{
Thread.sleep(1000);
}
catch(InterruptedException ex){
Thread.currentThread().interrupt();
}
// once the sleep finishes, the text from the JButtons is removed.
pickedcardbuttons[0].setText("");
pickedcardbuttons[1].setText("");
}
}
The program works exactly how I want it to, the only problem is that the program doesn't give enough time to actually display the text.
This is what happens:
The buttons before they are clicked
After one button is clicked (ok so far)
After two buttons are clicked (this is what you see during the sleep), as you can see, the animation is cut halfway through
and then the buttons return to not having any text.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…