嘿伙计们我正在尝试制作匹配卡片的游戏。 如果两张牌匹配,用户获得一个点并且卡片保持可见,否则翻转它们(或setText(""))我做了关于摇摆睡眠的研究,但我不确定如何实现它我的代码。我尝试了一切,但我不能让它发挥作用。我在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("");
}
}
}
}
}
}
};
答案 0 :(得分:1)
我“想”你应该做的更像是......
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
的{{1}}方法,允许您重置UI的状态...
问题是我在循环内部并且只能在单击时访问row和col
然后创建一个actionPerformed
,其中包含所需信息并在调用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