user3887735
user3887735

Reputation: 1

Java Timer Not Functioning

I recently made this program to count the seconds passing by but unfortunately, no print statement is showing. What is my problem here?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class MizohSoftware extends JFrame {

private class TimerListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        int time = 0;
        int inc = 1;
        time += inc;
        System.out.println(time + "seconds has passed");
    }
}

public void starttimer() {
    int delay = 1000;
    Timer display = new Timer(delay, new TimerListener());
    display.start();
}

public static void main(String[] args) {
    MizohSoftware MizohSoftware = new MizohSoftware();
    MizohSoftware.starttimer();
    }
}

Upvotes: 0

Views: 48

Answers (1)

Dave Newton
Dave Newton

Reputation: 160271

Your program ends before the timer event has a chance to fire.

E.g., add the following to your main:

  public static void main(String[] args) {
    MizohSoftware MizohSoftware = new MizohSoftware();
    MizohSoftware.starttimer();
    Thread.sleep(5000);
  }

This is probably not the behavior you want still; you need to read more about how the Java Swing event loop etc. works.

Upvotes: 1

Related Questions