繁体   English   中英

获取 titledPane JAVAFX 中复选框的选中值

[英]Get the checked value of a checkbox in a titledPane JAVAFX

所以我有一个 JavaFX 代码,它创建一个带有 TitledPanes 的手风琴,每个 TitledPane 都有一个复选框: 带有 TitledPanes 和 CheckBox 的手风琴

所以我的问题是有什么方法可以在单击按钮后获取这些复选框的值:即:我选择一个特定的复选框,当我单击一个按钮时,它会向我显示所有的复选框值

这是代码:

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

我强烈建议为这样的应用程序构建合适的对象模型。 每个TitledPane依赖于一个字符串(用作paths映射中的键)、一个Path 、一个HttpMethod和一个Operation 所以我将从一个封装这些数据的类开始。

我已将此称为Request ,但它可能不是最合适的名称。

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

}

如果您希望这些属性在 UI 中可编辑,您可以使用 JavaFX 属性而不是普通值来表示它们。

现在您可以遍历 Swagger API 返回的数据结构并创建一个简单的Request列表:

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

要跟踪复选框选择了哪些项目,请创建一个Set来保存所选项目:

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

然后每次创建复选框时,向其selectedProperty()添加一个侦听器,以从该集合中添加或删除相应的Request

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

}

如果您希望能够独立于用户操作复选框的状态,您可以使用ObservableSet ,并添加一个监听器来更新另一个方向的复选框状态:

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

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

}

使用此设置,您可以通过操作selectedRequests集来更改复选框的状态,例如:

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

这可能对 UI 中的其他控件有用。

现在在按钮的处理程序中,您可以遍历选定的请求集并执行您需要的任何操作:

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

把它们放在一起,它看起来像:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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