Java 如何停止计时器?

Java 如何停止计时器?,java,timer,Java,Timer,我试着停止计时器,但我没有成功。当标签离开屏幕时,我需要停止计时器(x外部ActionListener执行在while循环中继续,以便x递减到特定值(例如while(x>0))。这发生在EDT上。唯一似乎递减x的代码在生成的计时器中,但计时器在EDT上运行其代码,因此它必须等待a完成,因此x永远不会递减。换句话说,根据提供的信息,它是su请确认已发布的代码锁定了EDT 不清楚你到底在做什么,但是考虑创建一个减去X的定时器,并在满足条件时停止。例如: private void jButton1Ac

我试着停止计时器,但我没有成功。当标签离开屏幕时,我需要停止计时器(x外部
ActionListener
执行在while循环中继续,以便
x
递减到特定值(例如
while(x>0)
)。这发生在
EDT
上。唯一似乎递减
x
的代码在生成的
计时器中,但
计时器在
EDT
上运行其代码,因此它必须等待a完成,因此
x
永远不会递减。换句话说,根据提供的信息,它是su请确认已发布的代码锁定了EDT

不清楚你到底在做什么,但是考虑创建一个减去X的定时器,并在满足条件时停止。例如:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    x=365;   //horizontal position
    y=(int) (Math.random() * 365);  // random vertical position
    final Timer timer=new Timer(50,new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            jLabel1.setLocation(x,y);
            rand=(int)(Math.random()*10); //random speed to the left
            x=x-rand;
            if ( x <= 0 ){
                timer.stop();
            }
        }
    });
    timer.start();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
x=365;//水平位置
y=(int)(Math.random()*365);//随机垂直位置
最终计时器=新计时器(50,新ActionListener(){
已执行的公共无效行动(行动事件ae){
jLabel1.设定位置(x,y);
rand=(int)(Math.random()*10);//向左的随机速度
x=x-rand;
如果(x?
while(x>0){
while循环的目的是什么?它将在x之后终止
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    x=365;   //horizontal position
    y=(int) (Math.random() * 365);  // random vertical position
    final Timer timer=new Timer(50,new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            jLabel1.setLocation(x,y);
            rand=(int)(Math.random()*10); //random speed to the left
            x=x-rand;
            if ( x <= 0 ){
                timer.stop();
            }
        }
    });
    timer.start();
}