I have 2 buttons, when first button is clicked, it runs an infinite loop and I want it to stop when i click the second button. What is the proper way to do this since I'm new on using java.
I know this wrong but I just want to make clear what I'm trying to do
private void button1_buttonActionPerformed(java.awt.event.ActionEvent evt) {
while( !button2.isClicked() ) {} }
edited
here's what i have try
boolean sthap = false;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
while(!sthap){
System.out.println("run");
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
sthap=true;
}
still. It stucks on the loop
edited2
boolean sthap = false;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
runrun();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
sthap=true;
}
public void runrun(){
while(!sthap){
System.out.println("run");}
}
it still stuck
define a flag variable like;
boolean isBUttonClicked = false;
and in your while loop
use if statement like
while(true){
if(isButtonClicked){
isButtonClicked = false;
break;
}else{
//do your job
}
}
in the second button action performed method
use isButtonClicked and make it true like
isButtonClicked = true;
Try this
boolean sthap = false;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new Thread(new Runnable() {
@Override
public void run() {
while (!sthap) {
System.out.println("run");
}
}
}).start();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
sthap = true;
}
Declare a static variable like this boolean flag=false
outside the button methods. Then inside button 1,
private void button1_buttonActionPerformed(java.awt.event.ActionEvent evt) { while( !flag ) {} }
and inside button2,
private void button1_buttonActionPerformed(java.awt.event.ActionEvent evt) { flag = true}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.