0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@j.doe This error was hidden because of bad formatting. Make use of autoformat in whatever IDE you are using.
0
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

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.