摆动计时器问题 - 停止计时器

时间:2016-11-05 13:27:27

标签: java swing timer

我一直试图停止计时器并解决这个问题已经好几天了,遗憾的是没有运气,希望有人能够提供帮助。

这个想法是使用计时器点击一个增加文本字段值的按钮,所以我在开始按钮中有计时器,我希望在停止按钮中停止它。

这是我的开始按钮背后的代码:

private void btStartTimerActionPerformed(java.awt.event.ActionEvent evt) { 

        javax.swing.Timer tm = new javax.swing.Timer(100, new ActionListener(){
            public void actionPerformed(ActionEvent evt) {

                btAddOneActionPerformed(evt);
               }
        });
tm.start();

}

 private void btStopTimerActionPerformed(java.awt.event.ActionEvent evt) { 

}

1 个答案:

答案 0 :(得分:1)

您发布的代码中存在范围问题:您的Timer变量tm在开始按钮的actionPerformed方法中声明,因此仅在该方法中可见。因此,当在该方法之外时,您无法获得可行的参考。解决方案是将类级别的变量声明为私有实例(非静态)变量,并且只在开始按钮的动作侦听器中调用start()。这将使变量在整个类中可见,并且停止按钮的侦听器应该能够调用其方法。

如,

package pkg3;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.Timer;

public class TimerDeclaration {
    private static final int DELAY = 1000;

    // the tm2 variable is visible throughout the class
    private Timer tm2 = new Timer(DELAY, new TimerListener());

    private JButton btStartTimer1 = new JButton("Start Timer 1");
    private JButton btStartTimer2 = new JButton("Start Timer 2");

    public TimerDeclaration() {
        btStartTimer1.addActionListener(e -> btStartTimer1ActionPerformed(e));
        btStartTimer2.addActionListener(e -> btStartTimer2ActionPerformed(e));
    }

    private void btStartTimer2ActionPerformed(ActionEvent e) {
        tm2.start(); // tm2 is visible throughout your program
    }

    private void btStartTimer1ActionPerformed(ActionEvent e) {
        javax.swing.Timer tm = new javax.swing.Timer(100, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {

                // btAddOneActionPerformed(evt);
            }
        });
        tm.start(); // this is only visible inside here!!!
    }

    private class TimerListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub

        }
    }
}