嘿伙计们,我正在尝试制作一款匹配纸牌游戏。 如果两张卡片匹配,用户获得一个点并且卡片保持可见,否则翻转它们(或 setText("")) 我做了关于 Swing sleep 的研究,但我不确定如何在我的代码中实现它。我已经尝试了一切,但无法让它发挥作用。我在 main 中运行了这段代码。
ActionListener buttonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
JButton selectedButton = (JButton)e.getSource();
for (int row = 0; row < 6;row++){
for(int col = 0; col < 6; col++){
if (buttons[row][col] == selectedButton){
flipCard(row, col);
if(stack.empty()){
stack.push(row+","+col);
}else{
String word = (String)stack.pop();
String[] ar = word.split(",");
System.out.println(ar[0] + " " + ar[1]);
if (cardList.getCardNode(row, col).getLetter() ==
cardList.getCardNode(Integer.parseInt(ar[0]),
Integer.parseInt(ar[1])).getLetter()){
System.out.println("equal");
}else{
System.out.println("not equal");
//Compiler complains
//Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.Timer cannot be cast to javax.swing.JButton
Timer timer = new Timer(100 ,this);
timer.setRepeats(false);
timer.start();
buttons[row][col].setText("");
buttons[Integer.parseInt(ar[0])]
[Integer.parseInt(ar[1])].setText("");
}
}
}
}
}
}
};
最佳答案
我“认为”你应该做的事情更像是......
Timer timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
//Pop stack coordinates and set them back to ""
//setText on button clicked to ""
System.out.println(cardList.getCardNode(row, col).getLetter());
}
});
timer.setRepeats(false);
timer.start();
这将在 100 毫秒的延迟后调用 ActionListener
的 actionPerformed
方法,允许您重置 UI 的状态...
problem is I am inside the loop and have only access to row and col as it is clicked
然后创建一个 ActionListener
,它获取所需的信息,并在调用 actionPerformed
方法时对其采取行动...
public class FlipperHandler implements ActionListener {
private JButton[] buttons;
private int[] card1, card2;
public FlipperHandler(JButton[] buttons, int[] card1, int[] card2) {
this.buttons = buttons;
this.card1 = card1;
this.card2 = card2;
}
@Override
public void actionPerformed(ActionEvent evt) {
buttons[card1[0]][card1[1]].setText("");
buttons[card2[0]][card2[2]].setText("");
}
}
然后将其与计时器
一起使用...
Timer timer = new Timer(100, new FlipperHandler(buttons,
new int[]{row, col},
new int[]{Integer.parseInt(ar[0]), Integer.parseInt(ar[1])});
timer.setRepeats(false);
timer.start();
关于java - 如何让按钮setText hibernate ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29383046/