简体   繁体   中英

How to make a timer stop at a certain interval on java

I am using java swing with a JButton. When I press the button, I want a timer to start and count the number of times I press the button within a three second interval. I am trying to use a java.util.timer timer. Is this the right way to go? How do I start the timer and stop it after three seconds?

import javax.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.util.Timer;
import java.awt.*;
import java.awt.event.*;

public class button{
    public static void main(String[] args){
      JFrame frame = new JFrame("Test");
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.setSize(100, 75);
    JPanel panel = new JPanel();
    frame.add(panel);
    JButton button = new JButton ("                           ");
    button.setSize(300, 150);
    panel.add(button);
    button.addActionListener(new Action());
    frame.setAlwaysOnTop(true);
    frame.setBounds(1225, 675, 100, 75);        
    }
 static class Action implements ActionListener{
    public void actionPerformed (ActionEvent e){

    }
}
 public static int timer(){
     Timer timer = new Timer();      
     return 7;
 }
}

No need for timer here, I guess.

Just get the time initially, and whenever someone clicks check in your ActionListener implementation if it's in 3 secs from initial and increase click count if so.

If you don't need to track any further clicks, you can even unregister the action listener once you track the click you're not interested in any more.

UPDATE :

You claim you want to use Timer , however based on this one: http://www-mips.unice.fr/Doc/Java/Tutorial/uiswing/misc/timer.html Timer is to be used for delayed (or repetitive) tasks triggering. I don't think it fits your use case.

You can simply do this without timer :

// Time button being pressed
long milliseconds = 0;

JButton myButton = new JButton();

// Listener to click, press, release etc
myButton.addMouseListener(new MouseAdapter(){
    @Override
    public void mousePressed(MouseEvent e){
        milliseconds = System.currentTimeMillis();
    }
    @Override
    public void mouseReleased(MouseEvent e){
        long end = (milliseconds - System.currentTimeMillis()); // to seconds
        System.out.println(String.format("You have pressed the button for %ld milliseconds", end));
    }
});

For "within an interval of 3 seconds" I don't understand what you mean, but you can avoid printing the time if milliseconds > 3000 with my code.

I am going to guess that you want something else to happen after 3 seconds; ie, the user presses the button the first time, the timer starts, the user presses the button some more times, and after 3 seconds, you pop up a message saying how many times he pressed the button, or do something else after 3 seconds. These are the sorts of things that it is useful to say in your question description, otherwise people will say you don't need a timer.

And, described that way, it points out that the timer is not necessary just for counting clicks. If it were me, I would make a list and store the timestamp of each button click, and then, in the listener that fires after the timer, I would count the number of timestamps that fit within the window, not the number of times the user pressed the button. The problem is you could be off by one or two if the timer-firing-listener doesn't get scheduled before the last one or two button-clicked-listener executions.

To use it, create the time with the delay you want, add an action listener, and, in the action listener, pick up the list of button-clicks, analyze how many happen within the window, and then do whatever else you want.

static class Action implements ActionListener {
    int count;
    Long startTime;

    public void actionPerformed(ActionEvent e) {
        if (startTime != null && System.currentTimeMillis() - startTime <= 3000) {
            if (count == 2) {
                System.out.println("Bingo");
                count = 0;
                startTime = null;
            } else {
                count++;
            }
        } else {
            startTime = System.currentTimeMillis();
            count = 1;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM