从动作侦听器内部停止摆动计时器 [英] Stop a swing Timer from inside the Action Listener

查看:42
本文介绍了从动作侦听器内部停止摆动计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to stop a timer inside the the ActionListener. Below is the code of what i'm trying to do. I'm tring to stop the timer i created when a certain condition is met inside the actionPerformed method. timer.stop() does not work , the compiler does not let me do that.

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

Any help . suggestion , advice would be really helpful.

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 ):

Or, use the event object to get the source (and cast it, boo):

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

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

Or, keep the timer in an instance variable and you can reference it from your handler or have the handler call a method on your class which could stop/start it.

这篇关于从动作侦听器内部停止摆动计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆