N
N
nijobore2018-06-18 16:27:16
Java
nijobore, 2018-06-18 16:27:16

How to set a delay on the execution of a KeyListener?

I need that when the button is pressed, the action occurs after a specific time
and the next press can be made after a while
For example: When you press D, the variable I increases by 1 after 2 seconds, and the next press will be available after 3 seconds

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2018-06-18
@nijobore

ExecutorService to help you, plus do disable on your button.

myBtn.setEnabled(false);
ExecutorService executor = Executors.newFixedThreadPool(10);
Runnable runnableTask = () -> {
    try {
        TimeUnit.MILLISECONDS.sleep(2000);
        myBtn.setEnabled(true);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
};
executorService.execute(runnableTask);

PS. You can also run threads directly in swing - stackabuse.com/how-to-use-threads-in-java-swing

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question