【发布时间】:2013-06-08 22:42:46
【问题描述】:
我正在开发我的第一个 Swing 应用程序。这是一个使用扑克牌的记忆游戏。
我使用JLabels 模拟卡片并设置正面和背面的图标。每张卡片都有一个MouseListener,当用户点击时,我会检查两张卡片是否相同。如果它们不是同一张卡片,我想将这两张卡片显示一到两秒钟,然后在此延迟后,将图标改回来。
我尝试使用sleep、wait、invokeLater、invokeAndWait...但没有任何效果。
这是我的主要课程:
public class Main {
public static void main(String[] args) throws FontFormatException, IOException {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
MyApp window = new MyApp();
} catch ( FontFormatException | IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
MyApp 继承自 JFrame。在其中,我将所有卡片添加到一个面板中:
while ( cont < cardsInGame.size() ){
this.cardsInGame.get(cont).setBounds(x, y, 100, 140);
panelTablero.add(cardsInGame.get(cont));
cardsInGame.get(cont).addMouseListener(this);
x = x+108+5;
if ( (cont+1)%8 == 0 && cont != 0){
y = y+140+15;
x = 53;
}
cont++;
}
这是 MouseListener:
public void mouseClicked(MouseEvent e) {
Card selectedCard = (Card)e.getSource();
if (selectedCard != activeCard){
selectedCard.setIcon(new ImageIcon("img/"+selectedCard.getSuit()+selectedCard.getValue()+".png"));
//JOptionPane.showMessageDialog(vp, "Wait");
if ( activeCard != null && !activeCard.getPaired()) {
int result = activeCard.isPair(selectedCard);
pairsTried++;
if ( result != 0 ){
// PAIR
}
else{
// I WANT TO WAIT HERE
// NO PAIR
selectedCard.setIcon(new ImageIcon(CARD_BACK));
activeCard.setIcon(new ImageIcon(CARD_BACK));
}
activeCard = null;
}
else{
activeCard = selectedCard;
}
}
}
如果我在代码中调用JOptionPane.showMessageDialog(vp, "Wait"),一切正常。图标刷新,然后等待对话框确定。如果不是,则图标永远不会刷新(或超快且不显示)。
如何添加此延迟?
【问题讨论】:
-
使用摆动计时器。当计时器触发时,您会重置图标。
-
另外,可能example
-
感谢 MadProgrammer。这个例子对我来说是完美的。我已经在我的应用中尝试过,它可以工作!
标签: java swing icons delay jlabel