Stop a while loop with an awt button, problem
This is my simplified code: (how can I get this work?)
Code Java:
public class MyClass extends Applet implements ActionListener{
public void init(){
Button start = new Button("start");
Button stop = new Button("stop");
add(start);
add(stop);
start.addActionListener(this);
stop.addActionListener(this);
start.setActionCommand("start");
stop.setActionCommand("stop");
}
public void actionPerformed(ActionEvent ae){
String action = ae.getActionCommand();
if(action.equals("start")){
// start inputstream
while((len = is.read(buffer)) != -1){
// inputstream stuff
}
} else if(action.equals("stop")){
// stop while
}
}
}
thanks!
Re: Stop a while loop with an awt button, problem
I'm not convinced this is the best way to achieve your goal.
But to answer your question, you have to do the loop outside of your ActionListener (and not on the EDT). In that loop, check against a variable and exit the loop when it changes. Change that variable when you press the button.
Re: Stop a while loop with an awt button, problem
I created a new class to manage the input stream
but the button is still stuck.. I can't click it :confused:
Code :
public StreamClass{
public void doTheJob(){
// start inputstream
while((len = is.read(buffer)) != -1){
// inputstream stuff
}
}
}
...
Code :
public class MyClass extends Applet implements ActionListener{
public void init(){
Button start = new Button("start");
Button stop = new Button("stop");
add(start);
add(stop);
start.addActionListener(this);
stop.addActionListener(this);
start.setActionCommand("start");
stop.setActionCommand("stop");
}
public void actionPerformed(ActionEvent ae){
String action = ae.getActionCommand();
if(action.equals("start")){
StreamClass in = new StreamClass();
in.doTheJob();
} else if(action.equals("stop")){
// stop while
}
}
}
Re: Stop a while loop with an awt button, problem
If the task is time consuming, place it in a Thread of its own or use SwingWorker. As is, the time consuming task is on the EDT. Given the EDT is responsible for the GUI, no updates will be made until the task is complete - making it seem like your program froze. If you wish to stop the process in mid-stride, take KevinWorkman's advice re checking against a variable
Re: Stop a while loop with an awt button, problem
try using a boolean variable telling it to run while end = false and after your requirements set end to true
Re: Stop a while loop with an awt button, problem
Quote:
Originally Posted by
SHStudent21
try using a boolean variable telling it to run while end = false and after your requirements set end to true
That's pretty much exactly what I suggested in the first reply.