簡體   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