Reputation: 319
I am a beginner in java, I want to know is there any possible way to control a loop by clicking a button? I am creating a GUI, and it's supposed to run 10 times in the loop. Is there a way that I could have a button on the screen so that when the user presses, then it goes to the next iteration? Because currently everything just runs and executes once.
Upvotes: 3
Views: 1214
Reputation: 2772
You can use javaFX it's gonna replace javaswing very soon anyways plus it's cooler.
import javafx.scene.control.button
Button button = new Button("control");
int i = 0;
button.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
i++;
label.setText("i increased");
}
});
Upvotes: 0
Reputation: 11207
In your java class, you should define an attribute and each time you click on the button you add 1 to this attribute and do the action.
define an attribute in your class;
public int i = 0;
and create a button to be clicked on:
private void clickMeButtonActionPerformed(java.awt.event.ActionEvent evt) {
// code your action here:
this.i++;
}
Upvotes: 2
Reputation: 1101
You could have the loop wait for the button click, and then once it loops 10 times break the loop.
Upvotes: 1