In Java, let’s say I have a GUI with 2 buttons, Go and Pause.
When I press Go, “Hello” gets printed out over and over again. When I press Pause, “Hello” no longer gets printed to the screen.
Example: User presses Go button. “Hello” gets printed out for 1 minute until the user presses “Pause.”
What is the proper way to express this approach in Java? Is it equivalent to my commented pseudocode within the goButton source?
public void actionPerformed(ActionEvent e) {
if(e.getSource() == goButton)
{
// while user has not pressed the pause button
printHello();
}
else if(e.getSource() == pauseButton)
{
pause();
}
}
Thanks
In order to get this to work, in reasonable fashion, you will need a
Thread. This is executed in the background until such time as you decide to cancel/pause it.This is an EXTREMELY basic example. Normally I’d wrap the task and the GUI up in appropriate classes rather then accessing static references, but it gives a basic idea
Some further read:
Caveats
NEVER try and modify the GUI from any thread other then the Event Dispatching Thread.