1

So I wanted to make a timer to know when the user presses a button, however it doesn't seem to work the way it should.

When I put something in the public void actionPerformed() method it doesn't repeat at all - it should do it every 10th millisecond as I told it to. I have no clue what it might be because there are 0 warnings and 0 errors.

Here is the code:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class timertest {

    static Timer timer = new Timer(10,new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("test");

        }
    });

    public static void main(String[] args) { 
        timer.start();
    }
}
jva
  • 2,797
  • 1
  • 26
  • 41
Dubstepzedd
  • 148
  • 1
  • 9
  • this might help: https://stackoverflow.com/questions/18037576/how-do-i-check-if-the-user-is-pressing-a-key You need to link the ActionEvent with something. –  Sep 23 '19 at 15:13

1 Answers1

2

Because you are not starting it inside the Event Dispatch Thread.

public class TimerTest {

    static Timer timer = new Timer(10, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("test");

        }

    });

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> { //Run in EDT
            timer.start();
        });
    }
}

Also, have in mind that it is highly recommended (plus it helps us) to follow standard naming conventions - All class names should start with an Uppercase letter.

George Z.
  • 6,643
  • 4
  • 27
  • 47
  • Thanks! And sorry for the class name, I was in a hurry to test it out because my project that I was gonna use this with didn't work (and now it will)! I will keep it in mind next time :) – Dubstepzedd Sep 23 '19 at 18:43