I am writing a program which starts a loop when start button is clicked and I want to stop it with a stop button. Problem is when loop starts buttons do not work until loop is complete.
I’ve searched similar questions and understood the problem is loop is in actionPerformed but I couldn’t manage to take the loop outside of the actionPerformed.
I’ve tried that to make a new class and call for it etc but exactly same thing happened.
By the way I am a beginner at Java also stackoverflow and I am sorry if I did something wrong.
simply code:
OtherClass obj;
public void actionPerformed(ActionEvent e) {
if(e.getSource() == startButton) {
while(true) {
obj = new OtherClass();
obj.doJob();
}
else if(e.getSource() == stopButton) {
obj.stopLoop();
}
}
public class OtherClass {
private boolean isStopped = false;
public OtherClass() {
}
public void doJob(){
while(true) {
//loop...
if(isStopped) {
break;
}
}
}
You need to run doJob() in a separate thread (also called a “Worker thread”). Start the thread when the button is pressed and set the isStopped flag to true when it is pressed again. Be careful not to execute UI actions in the worker thread (such as updating progress bars) – there are special methods you need to call to update the UI from the worker thread.
Since this is a very general question (any my answer is very general too), I suggest to look out for “AWT ui thread”, “Worker thread” and “Java threading” in general on Google.
A good starting point could be Lesson: Concurrency in Swing