我已经实现了一个计时器来调用我的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();
答案 0 :(得分:2)
完成第一个计时器后,调用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();