简体   繁体   中英

Dynamically adding checkboxes in JavaFX

I'm trying to create a game prediction system in Java with GUI based on JavaFX using scene builder. It contains a HashMap containing a game object in which there is an ArrayList containing the participating athletes. Both of which will be decided by the user at runtime. Only a certain type of athletes will be eligible for participating in a certain type for a game, for example, swimmers will be able to participate only in swimming games. I can get the eligible athletes at by matching their types with game object and athlete object, but how do I create the checkboxes(for the eligible athletes at runtime?

You can use following approach to add or remove checkboxes at runtime

package com.grsdev.stackoverflow.question170919.pack02;


import javafx.application.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
 * @author gaurav salvi
 *
 */
public class JavaFxCheckBoxDemo extends Application{

    private static VBox root;

    private static CheckBox box=new CheckBox("Apple");

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

    @Override
    public void start(Stage stage) throws Exception {

        root=new VBox();

        Button button=new Button("            toggle         ");

        button.setOnAction(JavaFxCheckBoxDemo::buttonClicked);

        root.getChildren().add(button);
        root.getChildren().add(box);

        Scene value=new Scene(root,200,200);

        stage.setScene(value);

        stage.show();

    }

    private static void buttonClicked(ActionEvent event){

        if(root.getChildren().contains(box)){
            root.getChildren().remove(box);
        }else{
            root.getChildren().add(box);
        }
    }

}

I think, dynamically creating objects in Scene Builder and linking them in the controller on basis of their ID would very difficult if not impossible. One possible workaround for the given problem would be adding several static objects and set their visibility to hidden. As and how athletes were created and getting added to the ArrayList in the Game object I changed the visibility for the given checkbox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM