Get the checked value of a checkbox in a titledPane JAVAFX

maryem neyli :

So I have a JavaFX code that creates an Accordion with TitledPanes and each TitledPane have a checkBox: Accordion with TitledPanes and CheckBox

So my question is there is any way to get the value of those checkBoxes after a button click: i.e: I pick a specific checkboxes and when i click on a button it will pring me all the checkedBoxes values

and here is the code:

    import java.net.MalformedURLException;
import java.util.Map;

import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.Parameter;
import io.swagger.parser.SwaggerParser;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class GroupOfTitledPane extends Application {

    Stage stage;
    String ppaths[];
    String methods[];
    int i=0;

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

            //URL url= new URL(index.locationTextField.getText());
            //System.out.println(url);
            Swagger swagger = new SwaggerParser().read("https://petstore.swagger.io/v2/swagger.json");
            Map<String, Path> paths = swagger.getPaths(); 
            // Create Root Pane.
            VBox root = new VBox();
            root.setPadding(new Insets(20, 10, 10, 10));
            for (Map.Entry<String, Path> p : paths.entrySet()) {
                Path path = p.getValue();
                Map<HttpMethod, Operation> operations = path.getOperationMap();
                for (java.util.Map.Entry<HttpMethod, Operation> o : operations.entrySet()) {
                    CheckBox chk = new CheckBox();
                  chk.setText((o.getKey()).toString()+" : "+(p.getKey()).toString()+" : "+o.getValue().getSummary());
                TitledPane firstTitledPane = new TitledPane() ;
                BorderPane bPane = new BorderPane();
                 bPane.setRight(chk);
                 firstTitledPane.setGraphic(bPane);
                    VBox content1 = new VBox();
                    System.out.println("===");
                    System.out.println("PATH:" + p.getKey());
                    System.out.println("Http method:" + o.getKey());
                    System.out.println("Summary:" + o.getValue().getSummary());
                    content1.getChildren().add(new Label("Summary:" + o.getValue().getSummary()));
                    System.out.println("Parameters number: " + o.getValue().getParameters().size());
                    content1.getChildren().add(new Label("Parameters number: " + o.getValue().getParameters().size()));
                    for (Parameter parameter : o.getValue().getParameters()) {
                        System.out.println(" - " + parameter.getName());
                        content1.getChildren().add(new Label(" - " + parameter.getName()));
                    }
                    System.out.println("Responses:");
                    content1.getChildren().add(new Label("Responses:"));
                    for (Map.Entry<String, Response> r : o.getValue().getResponses().entrySet()) {
                        System.out.println(" - " + r.getKey() + ": " + r.getValue().getDescription());
                        content1.getChildren().add(new Label(" - " + r.getKey() + ": " + r.getValue().getDescription()));
                    }           
                    firstTitledPane.setContent(content1);
                    root.getChildren().addAll(firstTitledPane);

                }

            }


            ScrollPane scrollPane = new ScrollPane();
            scrollPane.setFitToHeight(true);
            scrollPane.setFitToWidth(true);
            Button terminer = new Button("Terminer");
            root.getChildren().addAll(terminer);
            root.setAlignment(Pos.BOTTOM_RIGHT);
            root.setSpacing(10);
            scrollPane.setContent(root);
            Scene scene = new Scene(scrollPane, 600, 400);
            stage.setScene(scene);
            stage.show(); 
            terminer.setOnAction(event -> {

            });

            }



    public static void main(String[] args) {
    Application.launch(args);
    }
} 
James_D :

I strongly recommend building a suitable object model for an application like this. Each of your TitledPane depends on a string (used as the key in the paths map), a Path, an HttpMethod, and an Operation. So I'd start with a class encapsulating those data.

I've called this Request, but it might not be the most appropriate name.

import java.util.Objects;

import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
import io.swagger.models.Path;

public class Request {

    private final String name ;
    private final Path path ;
    private final HttpMethod method ;
    private final Operation operation ;

    public Request(String name, Path path, HttpMethod method, Operation operation) {
        super();
        this.name = name;
        this.path = path;
        this.method = method;
        this.operation = operation;
    }

    public String getName() {
        return name;
    }

    public Path getPath() {
        return path;
    }

    public HttpMethod getMethod() {
        return method;
    }

    public Operation getOperation() {
        return operation;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, path, method, operation);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Request other = (Request) obj;
        return 
                Objects.equals(name, other.name) &&
                Objects.equals(path, other.path) &&
                Objects.equals(method, other.method) &&
                Objects.equals(operation, other.operation) ;
    }

}

If you want these properties to be editable in the UI, you would represent them with JavaFX properties instead of plain values.

Now you can iterate through the data structure returned by the Swagger API and create a plain list of Requests:

Swagger swagger = new SwaggerParser().read("https://petstore.swagger.io/v2/swagger.json");
Map<String, Path> paths = swagger.getPaths();

List<Request> requests = new ArrayList<>() ;

for (Map.Entry<String, Path> entry : paths.entrySet()) {
    Path path = entry.getValue();
    String pathName = entry.getKey() ;
    for (Map.Entry<HttpMethod, Operation> methodOp : path.getOperationMap().entrySet()) {
        HttpMethod method = methodOp.getKey() ;
        Operation operation = methodOp.getValue() ;
        requests.add(new Request(pathName, path, method, operation));
    }
}

To keep track of which items are selected by the check boxes, create a Set to hold the selected ones:

Set<Request> selectedRequests = new HashSet<>();

and then each time you create a check box, add a listener to its selectedProperty() to add or remove the corresponding Request from that set:

for (Request req : requests) {
    CheckBox chk = new CheckBox();
    chk.setText(req.getMethod() + " : " + req.getName() + " : " + operation.getSummary());

    chk.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
        if (isNowSelected) {
            selectedRequests.add(req);
        } else {
            selectedRequests.remove(req);
        }
    });

}

If you want to be able to manipulate the state of the checkboxes independently of the user, you can use an ObservableSet, and add a listener which updates the check box state in the other direction:

ObservableSet<Request> selectedRequests = FXCollections.observableSet();

and

for (Request req : requests) {
    CheckBox chk = new CheckBox();
    chk.setText(req.getMethod() + " : " + req.getName() + " : " + operation.getSummary());

    chk.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
        if (isNowSelected) {
            selectedRequests.add(req);
        } else {
            selectedRequests.remove(req);
        }
    });

    selectedRequests.addListener((Change<? extends Request> c) ->
        chk.setSelected(selectedRequests.contains(req)));

}

With this setup you can change the state of a check box just by manipulating the selectedRequests set, for example:

Request req = ... ;
// checks the corresponding check box: 
selectedRequests.add(req);
// unchecks the check box:
selectedRequests.remove(req);
// checks all check boxes:
selectedRequests.addAll(requests);
// unchecks all check boxes:
selectedRequests.clear();

which may be useful for other controls in the UI.

Now in your button's handler you can just iterate through the set of selected requests and do whatever you need:

terminer.setOnAction(event -> {
    selectedRequests.forEach(req -> {
        // Do whatever you need with the Request object here
        System.out.println(req.getMethod() + " : " + req.getName() + " : " + req.getOperation().getSummary());
    });
});

Putting it all together, it looks like:

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.Parameter;
import io.swagger.parser.SwaggerParser;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener.Change;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class GroupOfTitledPane extends Application {

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

        Swagger swagger = new SwaggerParser().read("https://petstore.swagger.io/v2/swagger.json");
        Map<String, Path> paths = swagger.getPaths();

        List<Request> requests = new ArrayList<>();

        for (Map.Entry<String, Path> entry : paths.entrySet()) {
            Path path = entry.getValue();
            String pathName = entry.getKey();
            for (Map.Entry<HttpMethod, Operation> methodOp : path.getOperationMap().entrySet()) {
                HttpMethod method = methodOp.getKey();
                Operation operation = methodOp.getValue();
                requests.add(new Request(pathName, path, method, operation));
            }
        }

        ObservableSet<Request> selectedRequests = FXCollections.observableSet();

        // Create Root Pane.
        VBox root = new VBox();
        root.setPadding(new Insets(20, 10, 10, 10));

        for (Request req : requests) {

            Operation operation = req.getOperation();
            CheckBox chk = new CheckBox();

            chk.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
                if (isNowSelected) {
                    selectedRequests.add(req);
                } else {
                    selectedRequests.remove(req);
                }
            });

            selectedRequests.addListener((Change<? extends Request> c) ->
                chk.setSelected(selectedRequests.contains(req)));

            chk.setText(req.getMethod() + " : " + req.getName() + " : " + operation.getSummary());
            TitledPane firstTitledPane = new TitledPane();
            BorderPane bPane = new BorderPane();
            bPane.setRight(chk);
            firstTitledPane.setGraphic(bPane);
            VBox content1 = new VBox();
            content1.getChildren().add(new Label("Summary:" + operation.getSummary()));
            content1.getChildren().add(new Label("Parameters number: " + operation.getParameters().size()));
            for (Parameter parameter : operation.getParameters()) {
                content1.getChildren().add(new Label(" - " + parameter.getName()));
            }
            content1.getChildren().add(new Label("Responses:"));
            for (Map.Entry<String, Response> r : operation.getResponses().entrySet()) {
                content1.getChildren().add(new Label(" - " + r.getKey() + ": " + r.getValue().getDescription()));
            }
            firstTitledPane.setContent(content1);
            firstTitledPane.setExpanded(false);
            root.getChildren().addAll(firstTitledPane);

        }

        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setFitToHeight(true);
        scrollPane.setFitToWidth(true);
        Button terminer = new Button("Terminer");
        root.getChildren().addAll(terminer);
        root.setAlignment(Pos.BOTTOM_RIGHT);
        root.setSpacing(10);
        scrollPane.setContent(root);
        Scene scene = new Scene(scrollPane, 600, 400);
        stage.setScene(scene);
        stage.show();
        terminer.setOnAction(event -> {
            selectedRequests.forEach(req -> {
                // Do whatever you need with the Request object here
                System.out.println(req.getMethod() + " : " + req.getName() + " : " + req.getOperation().getSummary());
            });
            // this will clear all the checkboxes:
            selectedRequests.clear();
        });

    }

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=340828&siteId=1