当前位置: 首页 > 面试题库 >

从动作侦听器内部停止摆动计时器

傅啸
2023-03-14
问题内容

我正在尝试在ActionListener中停止计时器。以下是我正在尝试执行的代码。我打算停止在actionPerformed方法内满足特定条件时创建的计时器。timer.stop()不起作用,编译器不允许我这样做。

任何帮助。建议,建议将非常有帮助。

public class ToggleAnnotationsAction extends IdentifiedMultiAction {
    //This status indicates if the Toggle action has been completed

/**
 * Defines the toggling direction of a <code>ToggleAnnotationAction</code> instance.
 */
public static enum Direction {FORWARD, BACKWARD};
private Direction myDir;

/**
 * Create an action with the direction presets given by the provided <code>Enum</code>.
 * 
 * @param dir An <code>Enum</code> defined in this class which maps to the correct direction of toggling
 * @see behaviors.multiact.IdentifiedMultiAction#IdentifiedMultiAction(Enum)
 */
public ToggleAnnotationsAction(Direction dir) {
    super(dir);
    this.myDir = dir;
}

/**
 * Performs the toggling, moving the audio position to the next/previous annotation.
 * 
 * Afterward sends an update to all <code>UpdatingActions<code>.
 *
 * Since the waveform display autonomously decides when to paint itself, this action may not result in an instant visual change.
 * 
 * <p>Prints warnings if an appropriate Annotation could not be found, despite the action being enabled.
 * 
 * @param e The <code>ActionEvent</code> provided by the trigger
 */
public void actionPerformed(ActionEvent e) {
    //Reset Status to 0 
    status =0;


    Annotation ann = findAnnotation(myDir, CurAudio.getMaster().framesToMillis(CurAudio.getAudioProgress()));
    if(ann == null) {
        System.err.println("It should not have been possible to call " + getClass().getName() + ". Could not find matching annotation");
    }
    else {
        final long approxFrame = CurAudio.getMaster().millisToFrames(ann.getTime());
        final long curFrame = CurAudio.getAudioProgress();
        if(approxFrame < 0 || approxFrame > CurAudio.getMaster().durationInFrames() - 1) {
            GiveMessage.errorMessage("The annotation I am toggling to isn't in range.\nPlease check annotation file for errors."); 
            return;
        }

             Timer timer = new Timer(10, new ActionListener() {
                 private long panFrame = curFrame;
                 private long endFrame = approxFrame;
                 public void actionPerformed(ActionEvent evt) {

                     if(myDir == Direction.FORWARD){
                         if (panFrame >= endFrame) {

                             //How do i Stop my timer here ? 
                             return;
                         }
                         CurAudio.setAudioProgressWithoutUpdatingActions(panFrame);
                         panFrame += 4000;
                    }
                 else if(myDir == Direction.BACKWARD){
                     if (panFrame <= endFrame) {

                        // How do i Stop my timer here ? 
                         return;
                     }
                     CurAudio.setAudioProgressWithoutUpdatingActions(panFrame);
                     panFrame -= 4000;
                }
             }

         }
         );

         timer.start();

      }
    MyFrame.getInstance().requestFocusInWindow();
}


/**
 * A forward (backward) <code>ToggleAnnotationsAction</code> should be enabled only when audio is open, not playing, and when there is an annotation following (preceding) the current position.
 */
@Override
public void update() {
    if(CurAudio.audioOpen()) {
        if(CurAudio.getPlayer().getStatus() == PrecisionPlayer.Status.PLAYING) {
            setEnabled(false);
        }
        else {
            double curTimeMillis = CurAudio.getMaster().framesToMillis(CurAudio.getAudioProgress());
            if(findAnnotation(myDir, curTimeMillis) != null) {
                setEnabled(true);
            }
            else {
                setEnabled(false);
            }
        }
    }
    else {
        setEnabled(false);
    }
}

/**
 * Finds the next/previous <code>Annotation</code> relative to a certain audio position in milliseconds.
 * 
 * @param dir The direction of movement
 * @param curTimeMillis The present time in milliseconds
 * 
 * @return In principle, the <code>Annotation</code> after/before <code>curTimeMillis</code>
 */
private Annotation findAnnotation(Direction dir, double curTimeMillis) {
    Annotation[] anns = AnnotationDisplay.getAnnotationsInOrder();
    if(myDir == Direction.FORWARD) {
        for(int i = 0; i < anns.length; i++) {
            if(anns[i].getTime() - curTimeMillis > 1) {
                return anns[i];
            }
        }
    }
    else {
        for(int i = anns.length - 1; i >= 0; i--) {
            if(curTimeMillis - anns[i].getTime() > 1) {
                return anns[i];
            }
        }
    }
    return null;
}

}

在此先感谢克里希南


问题答案:

也可能:

final Timer timer = new Timer(10, null);
timer.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        (as in the question, except that you can refer to timer here)
    }
});

或者,使用事件对象获取源(并将其 强制转换为boo ):

final Timer timer = new Timer(10, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        ((Timer)evt.getSource()).stop();
    }
});

或者,将计时器保留在实例变量中,您可以从处理程序中引用它,或者让处理程序在您的类上调用一个可以停止/启动它的方法。



 类似资料:
  • 我正在用摇摆计时器打卡NetBeans: 我只是用System.out.print来测试程序,它不是真正程序的一部分。我调用停止()方法,但计时器继续计数。此外,我通过但它的计数速度是原来的两倍。有人能帮忙吗? 编辑: 这是我的计时器(有点像SSCCE): 它不能正常工作,因为秒没有出现,但它确实显示了20次,这就是我想要的。这只是在它自己的应用程序中,在我的实际程序中更容易看到问题。 我注意到游

  • 问题内容: 有人可以教我如何使用a 来达到以下目的: 当我单击鼠标时,我需要一个开始动画的多边形(例如旋转等简单动画);当我再次单击时停止动画。 我对理解工作方式没有任何问题,但对于实际的动画来说,没有任何问题。我尝试在方法中用while块模拟动画,在该方法中我将绘制,擦除和重绘多边形(例如,模拟旋转),但是在while内,applet不会监听点击。它只会在片刻之后收听。单击鼠标时,我需要摆动计时

  • 问题内容: 使用Thread.sleep()时,JTextField.setText()出现问题。这是我正在制作的基本计算器。当输入字段中的输入格式不正确时,我希望“输入错误”出现在输出字段中5秒钟,然后将其清除。当我将文本一次设置为“INPUT ERROR”(输入错误)时,setText()方法_确实_起作用,并且通过打印之间的文本,我发现它确实可以与setText(“”)一起使用。当我将Thr

  • 我是一个java新手,我正在使用netbean创建一个调度程序。我的软件将从用户那里获取时间和操作,并将这些数据输入到单独的数组列表中。然后我使用javax.swing.timer启动倒计时计时器。当用户完成输入数据并点击“运行”按钮时,计时器将从数组列表中的第一个元素中获取运行时间并开始倒计时。当倒计时时间达到0时,计时器将从数组列表中的下一个元素中获取倒计时时间,依此类推。 我的问题是,计时器

  • 我最近一直在练习Java的swing特性,在我的一个扩展JPanel类的类中,我重写了方法,以便它将我的BufferedImage绘制到JPanel上。我也有一个方法在上面移动。在这个问题之前,我有一个问题,显示了移动的过程,因为它重新油漆太快。因此,我创建了一个名为的布尔变量,当图像仍在移动过程中时,该变量被设置为false。但是,现在我看到屏幕把整个图像拿走并放回原处,导致它眨眼。下面是我的基

  • 问题内容: 我需要一些有关在PHP中启动和停止计时器的信息。我需要测量从我的.exe程序开始(我在PHP脚本中使用函数)到完成执行并显示所花费的时间(以秒为单位)之后经过的时间。 我怎样才能做到这一点? 问题答案: 您可以使用并计算差异: 这是PHP的文档:http : //php.net/manual/zh/function.microtime.php