I am supposed to create an array of objects of type Buttons but the output it's just one button not multiple as it is supposed to. What Should I do?
int numberOfButtons = 20;
for (int i = 0; i < numberOfButtons; ++i) {
Button[] btn = new Button[numberOfButtons];
btn[i] = new Button();
btn[i].setText("Safe!");
btn[i].setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
FlowPane root = new FlowPane();
root.getChildren().addAll(btn[i]);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Button Blast!");
primaryStage.setScene(scene);
primaryStage.show();
}
root. You should also moveButton[] btn = new Button[numberOfButtons]before the for loop. Otherwise you're creating every variable within the for loop 20 times.root.getChildren().add(btn[i]);doesn't work anymore.for(Button b : btn) { root.getChildren().add(b); }. Or you could probably just doroot.getChildren().addAll(btn)without the for loop.