Search code examples
javaandroidmethodsactionlistenertiming

How do you execute one of two methods continuously when they run indefinitely and one based off a keypress event?


I am making an application that depends on a user pressing a key and time based events. The methods will run under two circumstances:

1: If the user presses a key the application prints foo.

2: If 3 seconds elapse then the application prints bar.

The first scenario runs independently of the the second, but the second is dependent on the first. The 3 second timer should reset every time the keypress event is called. After one of these two methods execute the application should return to a state where the application is waiting for one of the these two events to occur again.

Code might look similar to the following

@override
public void onPress(int i){
    System.out.print("foo");
}

public void printBar(){
    if(timeElapsed > 3){
        System.out.print("bar");
    }
}

So the on press event should occur normally when the key is pressed, but printBar should only run 3 seconds after the most recent execution of the most recent keyPress. Every execution of keypress should reset the printBar timer. Thank you for your help and let me know if I can provide better information.


Solution

  • Let me give you a general idea of how to do this.

    I assume that your keypress method works correctly (always prints foo when the key is pressed). What you need to resolve now, is how to reset the timer.

    I don't know what kind of timer you are using. But I guess because the app has something to do with key press events, and possibly you are using swing. I would recommend you to use java.swing.Timer.

    It is very easy to get how much time has elapsed using a swing timer.

    final Timer t = new Timer (3000, new ActionListener() {
        public void actionPerformed (ActionEvent e) {
            System.out.println("bar");
        }
    });
    

    This is very simple. 3000 means 3000 milliseconds or 3 seconds. When s seconds is elapsed, actionPerformed gets executed. In actionPerformed, you can just call your printBar (without the check!) or you can call System.out.println to meet the requirement.

    So now we have this set up, how are we going to reset it?

    Luckily, the Timer class provides a very helpful method, called restart. In your onPress method, just call this method

    @Override
    public void onPress () {
        System.out.println("foo");
        t.restart();
    }
    

    BOOM! You've done it!