如何停止计时器?

时间:2015-05-28 20:59:10

标签: java timer

我试图阻止计时器,但我无法管理它。我需要在标签离开屏幕时停止计时器(x <0)并再次启动计时器以将标签从框架的右侧移动到左侧。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    for(int i=0;i<10;i++){
      x=365;   //horizontal position
      while(x>0){
      randPosition=(int) (Math.random() * 365);  // random vertical position
      y=randPosition;
      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;
            }
             });
        timer.start();
         }
     }

    }

1 个答案:

答案 0 :(得分:1)

外部 ActionListener A 实施在x的while循环中继续递减到特定值(例如while (x>0) )。这发生在EDT上。似乎递减x的唯一代码在Timer生成的Timer内,但EDTx上运行其代码,因此必须等待要完成,所以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(); } 永远不会减少。换句话说,根据提供的信息,它暗示发布的代码使EDT陷入僵局。

目前还不清楚你究竟是在追求什么,但考虑创建一个递减X的单个Timer,并在满足条件时停止。例如:

    uint16_t mask = 0xffff << (16 - width);

    uint16_t buffer = (input[0] << 8) | uint[1];
    i += 2;

    int remaining = 16;

    while (i < input.Length) {
        while (remaining >= width) {
            output[p++] = (buffer & mask) >> (16 - width);
            buffer <<= width;
            remaining -= width;
        }
        // Refill the buffer. Since it is 16-bit wide there is a room
        // for an _entire_ input byte.
        buffer |= input[i++] << (8 - remaining);
        remaining += 8;
   }
   emit_remaining_bits(buffer, remaining);