Java Swing Timer Actionperformed doesn't get called - java

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!

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.

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...

Related

Why isn't my timer working?

public class TimerProgram extends JFrame {
public TimerProgram(){
int DELAY=1000;
Timer t = new Timer(DELAY,new TimerListener());
t.start();
}
class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
}
public static void main(String[]args){
new TimerProgram();
}
}
I am trying to make a timer that outputs every second the word hello, but it seems that when I type as the DELAY value 1000 , it outputs hello once and then it terminates. What am I doing wrong ? All help appreciated!
The JVM exited before the Timer fired.
Try:
t.setInitialDelay(0);
t.start();
to see the difference.
Or a better approach is to execute the code on the Event Dispatch Thread (EDT). All GUI code should execute on the EDT. By using SwingUtitities.invokeLater() you ensure the EDT has been created when your code executes:
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new TimerProgram();
}
});
Read the section from the Swing tutorial on Concurrency for more information about the EDT.

Actionlistener of a Timer object displays nothing

i am usin the timer class and in the docs it is written that i should import javax.swing.Timer to use it. does it mean that i can not use it in my normal java file? because i tried the below code, and it displays nothing:
static ActionListener timeStampListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("action listener");
for (int i = 1; i <= logfile.getTotalLines(); i++) {
System.out.println("Engine Time(ms): " +
logfile.getFileHash().get(i).getTimeStampInSec());
}
}
};
Timer t = new Timer(2, timeStampListener);
t.setRepeats(true);
t.start();
the problem is your main thread exist before starting timer thread .since your application is non-gui use util.Timer instead Swing.Timer ..if you want to work this code using swing timer then add a swing component .add new jframe() and see it's working ..you don't need swing.timer use util timer .
static ActionListener timeStampListener1 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("hi");
}
};
public static void main(String[] args) {
new JFrame(); //add this line
Timer t = new Timer(2, timeStampListener1);
t.setRepeats(true);
t.start();
}
or give some times by adding thread.sleep to timer to on and see it's working
Timer t = new Timer(2, timeStampListener1);
t.setRepeats(true);
t.start();
Thread.sleep(1000);
this is how can u use util timer for this
imports
import java.util.Timer;
import java.util.TimerTask;
code
public static void main(String[] args) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("action listener");
for (int i = 1; i <= logfile.getTotalLines(); i++) {
System.out.println("Engine Time(ms): "
+ logfile.getFileHash().get(i).getTimeStampInSec());
}
}
}, 500, 2);
}
No, it means that you should import which Timer class you will use. When you import javax.swing.Timer you specifies Timer class in javax.swing package. You can use it in your java file.
Anyway, have you tried not using static keyword with your timeStampListener?

Why does my java timer stop after seemingly random number of iterations?

I am trying to create a simple java program that will run indefinitely and output a number every second. I believe my code here should do this; however, it stops after the variable i gets to either 2, 3 or 4. Randomly. Most of the time it hits 3. I do not think that the program stopping is based on i at all, but something i'm overlooking perhaps.
All this program needs to do is spit out the second count using a timer. I feel like my code might be a little over complicated so please let me know if i'm making it too hard.
package testing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class driver {
static int delay = 1000; //milliseconds
private Timer timer;
int i = 0;
public driver(){
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println(i);
i++;
}
};
timer = new Timer(delay, taskPerformer);
timer.setInitialDelay(0);
timer.start();
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new driver();
}
});
}
}
Everything is just right in your program, but one.
Your program starts (from main() obviously), which starts the timer, timer method initiates the process of displaying time/number every second, and after that, the main thread dies! resulting in completion of program execution.
So to avoid this you simply can keep main thread busy.
Here's the simplest way :
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
driver d = new driver();
}
});
for(;;); // <-- **Check this out :D**
}

Counting and printing time in java using swing

I'm trying to implement a timer using one thread and print it on a JButton using another thread.
my class for time is like this:
public class Time extends Thread
{
int counter = 0;
public String currentTime = new String();
public String printFormat(int second)
{
return String.format("%d:%d", second/60, second%60);
}
synchronized public void count(int minute) throws InterruptedException
{
minute *= 60;
while(minute >= 0)
{
wait(1000);
minute--;
currentTime = printFormat(minute);
System.out.println(currentTime);
}
}
and my main thread is like this:
button.setText(time.currentTime);
what is wrong with this piece of code?
"if you can explain it using java swing timer , I would appreciate that"
If you want to use a javax.swing.Timer do the following, it really simple.
The same way you set a ActionListener to a button, you do the same for the timer. Except instead of the button firing the event, it's fired by the timer, every duration period you set for it.
In the case of a clock like timer, you would set it to 1000,
indication do something every 1000 milliseconds.
In this particular
example, I just set the text of the button with a count value that I
increment by one every time the timer event is fired. Heres the Timer code
Timer timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
button.setText(String.valueOf(count));
count++;
}
});
timer.start();
As you can see it' pretty simple
You can run this example
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ButtonTimer {
private JButton button = new JButton(" ");
private int count = 1;
public ButtonTimer() {
Timer timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
button.setText(String.valueOf(count));
count++;
}
});
timer.start();
JFrame frame = new JFrame();
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonTimer();
}
});
}
}
If you want help trying to figure out your current code, consider posting a runnable program we can test out. So we can see where you're going wrong.
Here's a tutorial on Concurrency With Swing

Can it be done in a more elegant way with the Swing Timer?

Bellow is the code for the simplest GUI countdown. Can the same be done in a shorter and more elegant way with the usage of the Swing timer?
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class CountdownNew {
static JLabel label;
// Method which defines the appearance of the window.
public static void showGUI() {
JFrame frame = new JFrame("Simple Countdown");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("Some Text");
frame.add(label);
frame.pack();
frame.setVisible(true);
}
// Define a new thread in which the countdown is counting down.
public static Thread counter = new Thread() {
public void run() {
for (int i=10; i>0; i=i-1) {
updateGUI(i,label);
try {Thread.sleep(1000);} catch(InterruptedException e) {};
}
}
};
// A method which updates GUI (sets a new value of JLabel).
private static void updateGUI(final int i, final JLabel label) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
label.setText("You have " + i + " seconds.");
}
}
);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showGUI();
counter.start();
}
});
}
}
Yes you SHOULD use a Swing Timer. You SHOULD NOT, use a util Timer and TimerTask.
When a Swing Timer fires the code is executed on the EDT which means you just need to invoke the label.setText() method.
When using the uitl Timer and TimerTask, the code DOES NOT execute on the EDT, which means you need to wrap your code in a SwingUtilities.invokeLater to make sure the code executes on the EDT.
And that is way using a Swing Timer is shorter and more elegant than your current approach, it simplifies the coding because to code is executed on the EDT.
You could make it a little more elegant by using Timer with an appropriate TimerTask.
Yes, use a timer. updateGUI would be the code for the timer task, but it will need some changes as you won't be able to pass in i for each call since you just get a run() method.

Categories