2

我已经实现了一个计时器来调用我的 alert() 方法。从数据库中检索计时器的持续时间。当我将持续时间设置为 1 分钟时,计时器每隔一分钟调用一次 alert()。当我再次将持续时间设置为 5 分钟时,1 分钟计时器不会停止。所以现在我有 2 个正在运行的计时器。如何删除以前的计时器?谢谢。

private void getDuration() 
{       
    durationTimer = new javax.swing.Timer(durationDB, new ActionListener() 
    {               
        public void actionPerformed(ActionEvent e) 
        {       
            alert();      
        }     
    });                 
    durationTimer.stop();

    try
    {   
        // Connection to the database
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/smas","root","root");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM alertduration");    

        while (rs.next()) 
        {
            durationDB = rs.getInt("duration");     
        }   

        con.close();            
    }

    catch(Exception ea)
    {
        JOptionPane.showMessageDialog(watchlist, "Please ensure Internet Connectivity ", "Error!", JOptionPane.ERROR_MESSAGE);
    }           


    durationTimer = new javax.swing.Timer(durationDB, new ActionListener() 
    {               
        public void actionPerformed(ActionEvent e) 
        {       
            alert();      
        }     
    });         

    durationTimer.start();
4

1 回答 1

3

完成第一个计时器后调用 stop() 方法。将计时器设为全局并重用它,而不是每次持续时间更改时都创建一个新计时器,这也可能是值得的。请参阅:http ://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html

例子:

durationTimer = new javax.swing.Timer(duration, new ActionListener() {               
    @Override
    public void actionPerformed(ActionEvent e) {       
        alert();
    }     
});                 

durationTimer.start();

//wait for duration to change
durationTimer.stop();
durationTimer.setDelay(duration);
durationTimer.start();
于 2012-05-21T16:06:29.237 回答