Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Javafx -- dynamically adding buttons and calling setonAction() on it

So I am currently doing a personal project where I encountered this situation... A user inputs a data (numeric) this generates a no. of Labels and buttons on to a javafx scene.. Now What i did is inside a controller's Initialization interface I started a for loop that run to the size of data (numeric) that the user inputs, inside the loop I was able to create labels and buttons dynamically...for instance this way -- gridPane is a id of GridPane from an fxml file...

@FXML private GridPane gridpane; . <....Some Code goes here...> . for (int i=0 ; i < userInput ; i++){ gridPane.add (new Label (String.valueOf(101+i)) , 0, i ) ; gridPane.add (new Button ("Describe"), 1, i ) ; }

Now my question is how do I call setOnAction() on this buttons...

2 Answers

Ok I figured even efficient method to solve this solution...

I created an arrayList added buttons to it then added on gridPane and now I can use ..

ArrayList<Button> buttons = new ArrayList<>();

gridPane.add(buttons.get(i), 1,i);

buttons.get(i).setOnAction( e -> { .. insert if conditions here.. or search for what button user clicked in a for each loop via e.getsource() function...}

You could store the Button on each loop in a local variable so you can both add it to the GridPane and call setOnAction.

Button button = new Button("Describe");
gridPane.add (button, 1, i );
button.setOnAction();

Also GridPane as a Parent has a getManagedChildern() method that returns a List of what's inside.

yup but then how should I know which button user clicked ... say for example userInuput was 5 then we get 5 buttons but then how can i know user clicked 2nd button?? Hope you understand what I'm asking here now..