如何停止javax.swing.Timer

geshenghua 2011-02-16 07:04:49
public void shiftRing(Tower a, Tower b) {
done = false;
temp = a.rings.pop();
currentX = temp.x;
from = a;
to = b;
to.rings.push(temp);
timer = new Timer(1, new ActionListener() {

public void actionPerformed(ActionEvent e) {
if (done) {timer.stop();}

int incre = 1;
if (to.baseX - from.baseX < 0 ) incre *= -1;

if (temp.y <= 20) up = true;
if (temp.x == to.baseX + currentX - from.baseX) move = true;
if (temp.y == to.baseY - temp.height) down = true;

if (!up) temp.setLocation(temp.x, temp.y - 1);
else if(!move) temp.setLocation(temp.x + incre , 20);
else if(!down) temp.setLocation(temp.x, temp.y + 1);
else {
up = false;
move = false;
down = false;
done = true;
}
System.out.println(temp.getLocation());
repaint();
}
});
timer.start();
}

如题,我用了 if (done) {timer.stop();}
但是还是停止不了这个timer,我想在done为真之后就退出timer和shiftRing这个方法,求助各位~~
...全文
369 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
Mybeautiful 2011-02-23
  • 打赏
  • 举报
回复
timer.stop()很好用。
dracularking 2011-02-17
  • 打赏
  • 举报
回复
但不管怎样,我想某些特殊情况无法查出编译问题,就会在运行期暴露,结果的一致性恰一定程度上证明了可能某个特定原因
dracularking 2011-02-17
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 geshenghua 的回复:]

引用 3 楼 dracularking 的回复:
timer = new Timer(1, new ActionListener() {

public void actionPerformed(ActionEvent e) {
if (done) {timer.stop();}

这里能编译成功吗 调用stop时的timer还未初始化完成呢

可以编译成功,但是停止不了。
[/Quote]
是吗 你是用什么编译的 奇怪啊
这里timer.stop()是位于Timer的构造体中,应会提示:timer may not have been initialized 我实际试验下来也是如此,完整的程序看一下就知道了
阿星777 2011-02-17
  • 打赏
  • 举报
回复
确定timer.stop();执行了没有,
shenzhenggg 2011-02-17
  • 打赏
  • 举报
回复
定时器都不清楚 好好看看jdk timer
Inhibitory 2011-02-16
  • 打赏
  • 举报
回复
if (done) {
System.out.println("Stop()"); // 随便打印点东西看一下是否真的退出
timer.stop();
}
wxslzmb 2011-02-16
  • 打赏
  • 举报
回复
是不是有个cancel方法?
geshenghua 2011-02-16
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 b87936260 的回复:]
你的done为true了吗?
[/Quote]
是的。
geshenghua 2011-02-16
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 dracularking 的回复:]
timer = new Timer(1, new ActionListener() {

public void actionPerformed(ActionEvent e) {
if (done) {timer.stop();}

这里能编译成功吗 调用stop时的timer还未初始化完成呢
[/Quote]
可以编译成功,但是停止不了。
dracularking 2011-02-16
  • 打赏
  • 举报
回复
timer = new Timer(1, new ActionListener() {

public void actionPerformed(ActionEvent e) {
if (done) {timer.stop();}

这里能编译成功吗 调用stop时的timer还未初始化完成呢
b87936260 2011-02-16
  • 打赏
  • 举报
回复
你的done为true了吗?
zqfddqr 2011-02-16
  • 打赏
  • 举报
回复
你的监听是不是没触发

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧