我正在制作一个简单的目标射击游戏.我在标签内部有一个倒计时器,一个在面板内随机位置闪烁的物体.每次我点击对象,对象的计时器停止使得该对象也停止,但倒数计时器没有,这是我的问题.我想倒数计时器也应该停止.
有人可以帮我解决这个问题吗?
这是代码:
private void starting()
{
new Timer(TIMER_PERIOD, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (count++ < MAX_COUNT)
{
String text = "Time remaining: (" + (MAX_COUNT - count) + ") seconds left";
setCountDownLabelText(text);
Date date = new Date();
setCountDownPanelText(date);
}
else
{
((Timer) e.getSource()).stop();
randomTimer.stop();
JOptionPane.showMessageDialog(null, "Game Over");
System.exit(0);
}
}
}).start();
}
Run Code Online (Sandbox Code Playgroud)
令我感到震惊的是你根本不理解代码,你不知道创建的匿名类正在扩展Timer,它(如果你看过文档)有一个功能stop()可以满足你的要求.
您需要存储对Timer的引用.
private javax.swing.Timer timer;
private void starting() {
timer = new Timer(TIMER_PERIOD, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// do stuff
// stop the timer
timer.stop();
// do other stuff
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
728 次 |
| 最近记录: |