Odrobine zamieszane w tym Twoim kodzie. Jesli uzywasz javax.swing.Timer nie potrzebujesz tworzyc obiektu klasy java.util.TimerTask. Wystarczy, ze przekazesz ActionListener, ktory bedzie sekwencyjnie "powiadamiany" przez Twoj timer, do czasu zatrzymania.
java.util.Timer mozesz uzyc, jesli chcesz wywolac tylko jedno zadanie po uplywie okreslonego czasu od konkretnej daty. Wtedy wlasnie potrzebny jest obiekt TimerTask.
Przykladowy sposob uzycia:
import java.util.Timer;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GridLayout;
import java.util.TimerTask;
class MyTimerTask extends TimerTask {
private JLabel label;
public MyTimerTask(JLabel label) {
this.label = label;
}
public void run() {
label.setText("[ akcja java.util.Timer wykonana ]");
}
}
public class TimerTest extends JFrame implements ActionListener {
private static final int DELAY = 5000;
private JButton b1;
private JButton b2;
private JLabel l1;
private JLabel l2;
private java.util.Timer timer1;
private javax.swing.Timer timer2;
private int counter;
public TimerTest() {
super("Test Timerow w Java");
setSize(600, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1 = new JButton("java.util.Timer");
b1.addActionListener(this);
b2 = new JButton("javax.swing.Timer");
b2.addActionListener(this);
l1 = new JLabel("[ pole zmian dla java.util.Timer ]");
l2 = new JLabel("[ pole zmian dla javax.swing.Timer ]");
JPanel panel = new JPanel(new GridLayout(2, 2, 5, 5));
panel.add(b1);
panel.add(l1);
panel.add(b2);
panel.add(l2);
getContentPane().add(panel);
}
public void actionPerformed(ActionEvent event) {
if(event.getSource() == b1) {
timer1 = new java.util.Timer();
timer1.schedule(new MyTimerTask(l1), DELAY);
l1.setText("[ oczekiwanie " + DELAY + "ms na Timer ]");
} else
if(event.getSource() == b2) {
if(timer2 != null && timer2.isRunning()) {
timer2.stop();
l2.setText("[ javax.swing.Timer zatrzymany ]");
} else {
counter = 0;
timer2 = new javax.swing.Timer(DELAY, this);
timer2.start();
l2.setText("[ oczekiwanie " + DELAY + "ms na Timer ]");
}
} else {
counter++;
l2.setText("[ akcja javax.swing.Timer wykonana (" + counter + ") ]");
}
}
public static final void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TimerTest().setVisible(true);
}
});
}
}