2016-11-05 157 views
0

我一直在试图停止计时器并解决这个问题,现在很多天,不幸的是没有运气,希望有人能够提供帮助。摆动计时器问题 - 停止计时器

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

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

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

为了更好的帮助下,考虑创建和张贴[最小,完整,可验证的示例程序(http://stackoverflow.com/help/mcve)。我们不想看到你的整个程序,而是你应该将你的代码压缩到仍然编译的最小位,没有额外的代码与你的问题无关,但仍然表明你的问题。通过简单地尝试隔离并暴露错误,您可能很好地解决了这个问题。 –

回答

1

你一定范围的问题你贴出代码:你的定时器变量,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 

     } 
    } 
} 
+0

我可以看一个例子吗? –

+0

@Jamesanderson:当然。请查看[这些链接](http://stackoverflow.com/search?q=user%3A522444+swing+timer)以及[Swing Timer教程](http://docs.oracle.com /javase/tutorial/uiswing/misc/timer.html) –

+0

你介意让我看看它是如何在我的代码中看到的吗? ,对不起,如果我有问题。 –