Oscar Chavez Oscar Chavez - 1 month ago 13
Java Question

Array of objects in JavaFX

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();
}

Answer

When you run in such problems the best thing is to get a paper and a pen and to write down what each line of your code does.

your complete code is within the loop. you should narrow it down so that in only contains this:

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!");
    }
});