-1

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();
}
3
  • 1
    You should probably close your for loop before you create root. You should also move Button[] btn = new Button[numberOfButtons] before the for loop. Otherwise you're creating every variable within the for loop 20 times. Commented Oct 28, 2016 at 21:22
  • Ok, so I did that... But then the method root.getChildren().add(btn[i]); doesn't work anymore. Commented Oct 28, 2016 at 22:03
  • So add another for loop like: for(Button b : btn) { root.getChildren().add(b); }. Or you could probably just do root.getChildren().addAll(btn) without the for loop. Commented Oct 28, 2016 at 22:07

2 Answers 2

1

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!");
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

I used JavaFx with Java8 (Stream) in order to solve your issue:

    FlowPane fPane = IntStream.range(1, 20)
            .mapToObj(value -> {

                Button button = new Button("Safe!");

                button.setOnAction(event -> {
                    System.out.println("Hello World!");
                });

                return button;

            }).reduce(new FlowPane(), (p, b) -> {

                p.getChildren().add(b);

                return p;
            }, (flowPane, flowPane2) -> flowPane2);

    Scene scene = new Scene(fPane, 300, 250);

    primaryStage.setTitle("Button Blast!");
    primaryStage.setScene(scene);
    primaryStage.show();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.