j.doe
j.doe

Reputation: 19

Adding an array of buttons to a Flow Pane

I need to add an array of 20 buttons to a flow pane. I have the array created but can't seem to get all of the buttons show up. Why is it only adding one button?

public class Activity4 extends Application 
{
@Override
public void start(Stage primaryStage) 
{
    Button[] btn = new Button[20];
    for(int i=0; i<btn.length;i++)
    {
        btn[i] = new Button();
        btn[i].setText("Safe!");
        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();
        btn[i].setOnAction(new EventHandler<ActionEvent>() 
        {
            @Override
            public void handle(ActionEvent event) 
                {
                    System.out.println("Hello World!");
                }
        });     
    }
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}    
}

Upvotes: 0

Views: 1373

Answers (2)

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.scene.control.Button;
public class Activity4 extends Application 
{
    @Override
    public void start(Stage primaryStage) 
    {
        Button [] btn = new Button[20];
        for(int i=0; i<btn.length;i++)
        {
            btn[i] = new Button();
            btn[i].setText("Safe!");

        }
        FlowPane root = new FlowPane();
        root.getChildren().addAll(btn);

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

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

   
    public static void main(String[] args) {
        launch(args);
    }    
}

enter image description here

Upvotes: 0

James_D
James_D

Reputation: 209340

On every iteration of the loop, you are creating a new FlowPane, and then creating a new Scene and setting it to the stage.

You need to create one FlowPane before the loop. In the loop, create the buttons, register the handler with them, and add them to the flow pane.

The after the loop, create the Scene with the flow pane, set it in the stage, and show the stage.

Upvotes: 1

Related Questions