Reputation: 101
So, I've been messing around with the Swing Timer in Java, trying to make a little time counter. However, the actionperformed method doesn't seem to react whenever I make a timer and let it run. Here's my simplified UI class:
public class UI implements ActionListener {
private int value = 0;
Timer timer = new Timer(5,this);
@Override
public void actionPerformed(ActionEvent e) {
value++;
System.out.println(value);
}
public void start() {
timer.start();
}
}
And this is what my launcher looks like:
public class Launcher {
public static void main(String[] args) {
UI ui = new UI();
ui.start();
}
}
When I run the launcher, nothing happens. I do know he creates the UI and lets the timer start, but the timer doesn't seem to call the Actionperformed method. I'm wondering why. It should show the value +1 every interval of 5 (miliseconds?).
Thanks in advance!
Upvotes: 0
Views: 563
Reputation: 7
hey i can help you out... you should do the following ;
firstly import the following ;
import java.awt.event.ActionEvent ;
import java.awt.event.ActionListener ;
import javax.swing.Timer ;
then initialize the timer at the end of the form like this ;
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new mainprogramme().setVisible(true);
}
});
}
private Timer timer ;
then after initializing the timer add a public class like following;
public class progress implements ActionListener {
public void actionPerformed(ActionEvent evt){
int n = 0 ;
if (n<100){
n++ ;
System.out.println(n) ;
}else{
timer.stop() ;
}
}
}
after you do this go to the j Frame>right click and select>Events>window>window Opened and type the following ;
private void formWindowOpened(java.awt.event.WindowEvent evt) {
timer = new Timer(100,new progress()) ;
and after you do all this take a button name it as anything and type the following in its void like following ;
timer.start();
AND THAT'S IT CODE IT AND THEN REPLY ME...
Upvotes: 0
Reputation: 388
Your program is exiting before the timer Thread has a chance to start. You should give a little time before exiting the main Thread to allow the timer Thread to keep running. Thread.sleep(100)
after ui.start()
should solve.
Upvotes: 1