user7503474
user7503474

Reputation: 13

How to make new button Objects using a for loop and display it using javafx

I am trying to display 9 buttons using javafx.

public class Main extends Application 
{
    public void start(Stage primaryStage) throws Exception 
    {

        Button[] button = new Button[10];
        Pane pane = new Pane(); 

        for( int i=0; i < 9; i++)
        {
            button[i].setText("hi");
            button[i].setText("hi");
            button[i].setLayoutX(i*10);

            System.out.println(button[i].getText());
            pane.getChildren().addAll(button[i]);                   
        }

        Scene scene = new Scene(pane); 
        primaryStage.setScene(scene);
        primaryStage.show();       


}

Upvotes: 0

Views: 1108

Answers (1)

azro
azro

Reputation: 54168

You create an array able to store Button element, but you never create the Button itself

So you have to do :

for( int i=0; i < 9; i++){
    button[i] = new Button();     // <-- here
    button[i].setText("hi");      // you have twice this line
    button[i].setLayoutX(i*10);

    System.out.println(button[i].getText());
    pane.getChildren().addAll(button[i]);                   
}

Also, if for other part you don't need to retrieve the button later, you don't need so store them and use an array, this will work :

for( int i=0; i < 9; i++){
    Button btn = new Button();     // <-- here
    btn.setText("hi");
    btn.setLayoutX(i*10);

    System.out.println(btn.getText());
    pane.getChildren().addAll(btn);                   
}

Upvotes: 2

Related Questions