0

I'm working on a Java project involving user interface, using the Button class and some action listeners. I have a few buttons (each with an action listener) and I want to add a timeout to the whole program. That means, if no button was clicked-on in a certain amount of time, a specific action should be performed.

I tried adding it among the basic while loop + isDisposed() function. To my knowledge, this loop checks multiple times whether a button was clicked-on. For some reason, I couldn't get the outcome I wanted. Is there a way to do so with the classes I mentioned? I also couldn't find any suitable functions in the Button class.

Dan
  • 21
  • 3

2 Answers2

0

Use a Swing Timer (javax.swing.Timer).

Instanciate it with new Timer(CERTAIN_AMOUNT_OF_TIME, e -> timeoutAction()) (If you have a function timeoutAction), disable repeating with setRepeats(false) and start() it.

When the user clicks a button, call restart() on it.

Also, you’re mentioning the Button class, which is an AWT class. I recommend using Swing’s JButton class instead.

Snowy_1803
  • 656
  • 2
  • 8
  • 24
0

It is highly probable that you are using swing, but since this is not specified, I will give you a general answer, with links to swing examples.

First of all, since all your button clicks will behave in a very similar manner, so you will need a custom ActionListener (example). Your custom action listener should perform the action, but set a timestamp or some kind of date value to the current moment. In parallel, you should have a heartbeat event, which periodically (frequently) runs and compares the current moment with the timestamp set by the last button click. And you can see an example of a periodic task here: How to schedule a periodic task in Java?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175