Several questions you need to ask your self...
How scalable is it? What are the performance considerations?
How scalable is it?
If you take a look at your current approach, you have a single ActionListener
monitoring ALL the buttons. What happens if you need to increase the number of Timers
to 20, 100, 1000? That's a lot of extra work and a very large if
statement.
Now, I'm particular about maintaining levels of responsibility and having had to maintain a multi-level if
statements within an ActionListener
before, really dislike this approach...
Instead, you could put everything (the buttons for example) in some kind of List
and loop over the list when the actionPerformed
method is called, but even that becomes difficult to manage and may not meet the requirements of your design in the long run. You may or can not allow the ActionListener
to know about your buttons or you can't access the List
due to reference issues, etc...
Personally, I would create two classes, a StartActionListener
and a StopActionListener
. These would take a reference to (at least) a Timer
.
This would mean, to add a new start button, you would simply need to create a new JButton
and create a new instance of StartActionListener
and register to the button. You would do a similar thing for the stop button, registering an instance of StopActionListener
with it.
This divorce the listener design from the application design, as the listeners won't actually need to care about the buttons at all, only the Timer
they are managing. It means that each listener is responsible for just one thing and provides a level of abstraction to the design, giving you freedom to choose how to actually implement the overall design/requirements.
You may also wish to take a look at How to use Actions which provides with the ability to provide configuration details for the action, making even easier to create controls.
What are the performance considerations?
Having multiple Timers
running may not scale well and will introduce performance issues as you increase their numbers, to the point where the UI updates begin to suffer.
It might be better to use a single Timer
which "ticks" at a regular interval and instead of creating a new Timer
, you would simply register a ActionListener
to a single Timer
.
This would possibly mean that the ActionListener
would need to maintain know when it was registered so it can determine the amount of time that has passed for each "tick", but this would a consideration of the context of the problem you are trying to solve. Equally, you could simply keep some kind of counter per ActionListener
.