如何停止计时器

时间:2015-12-11 21:26:42

标签: java multithreading timer

我有以下行动方法

public void actionPerformed(ActionEvent e) {

    Timer timer = new Timer();
    Object source = e.getSource();

    String stringfromDate = tffromDate.getText();
    String stringtoDate = tftoDate.getText();

    if (source == button) {
        // auto refresh begins
        int delay = 0; // 0 seconds startup delay
        int period = 7000; // x seconds between refreshes
        timer.scheduleAtFixedRate(new TimerTask()
        {
            @Override
            // i still have to truly understand what overide does however
            // netbeans prompted me to put this
            public void run() {

                try {
                    getdata(stringfromDate, stringtoDate);// run get data
                                                            // method
                } catch (IOException | BadLocationException ex) {
                    Logger.getLogger(JavaApplication63.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
            }
        }, delay, period);
    }

    if (source == button1) {
        timer.cancel();

        textarea.setText("");
    }
}

我的GUI上有2个按钮,一个叫做获取信息(按钮),另一个叫做清除信息(按钮1)。 我似乎无法得到我的清除信息(button1)来停止计时器并清除文本区域,以便可以执行新的搜索。我似乎无法让这个停止帮助赞赏。

1 个答案:

答案 0 :(得分:3)

考虑对代码的这些更改。主要是代码以不同的方式执行这些操作:

  • 将计时器的声明提升到班级,以便之前启动的相同计时器可以在以后取消。

  • 仅在按下开始按钮时才创建新计时器。

    //Pulled up for access to make canceable .
    protected Timer timer;
    
    public void actionPerformed(ActionEvent e) {
    
      Object source = e.getSource();
    
      String stringfromDate = tffromDate.getText();
      String stringtoDate = tftoDate.getText();
    
      if (source == button) {
        //Stop existing one before creating new.
        if(timer != null) {
            timer.cancel();
        }
        //Now make new
        timer = new Timer();
    
        // auto refresh begins
        int delay = 0; // 0 seconds startup delay
        int period = 7000; // x seconds between refreshes
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override 
            public void run() {
    
                try {
                    getdata(stringfromDate, stringtoDate);// run get data
                                                            // method
                } catch (IOException | BadLocationException ex) {
                    Logger.getLogger(JavaApplication63.class.getName()).log(Level.SEVERE, null, ex);
    
                }
    
            }
        }, delay, period);
      }
      if (source == button1) {          
        //NULLCHECK
        if(timer != null) {
            timer.cancel();
        }
        textarea.setText("");
      }
    }