как добавить панель поиска с помощью JavaFX (java) - PullRequest
1 голос
/ 27 апреля 2020

Поскольку вопрос нерешительный, мне нужен способ добавить панель поиска с помощью javaFX, поэтому я попробовал множество решений и нашел это: { ссылка }, но в ее случае она использует FilteredList которая дала ей возможность использовать метод setPredicate, но в моем случае я использую ObservableSet, так есть ли какое-либо решение добавить фильтр в ObservableSet, чтобы я мог добавить панель поиска? Вот мой код:

    public class Test extends Application {

String mainPath=index.target.getText() ;
String url=index.tst;
String notes = "";
String summary="";
String method="";
@Override
public void start(Stage stage) throws Exception {

    URL urlapi = new URL("https://developer.opentext.com/awd/resources/apis/cs-rest-api-for-cs-16-s/api-docs.json");
    List < Request > requests = new ArrayList < >();
    JSONParser parser = new JSONParser();
    String output = getUrlContents(urlapi.toString());
    Object obj = parser.parse(output);
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray apis = (JSONArray) jsonObject.get("apis");
    for(int i = 0; i<apis.size();i++) {

        JSONObject api = (JSONObject) apis.get(i);
        String path = (String) api.get("path");
        String apidesc = (String) api.get("description");
        path=path.replace("/", "");
        if (path.endsWith("}")) {
            path=path.replace(".{format}", ".json");
            String newurl = "https://developer.opentext.com/awd/resources/apis/cs-rest-api-for-cs-16-s/"+path;
            System.out.println(newurl);

            JSONParser parser2 = new JSONParser();
            String output2 = getUrlContents(newurl.toString());
            JSONObject jobj = (JSONObject) parser.parse(output2);
            JSONArray eapis = (JSONArray) jobj.get("apis");
            for (int n = 0; n < eapis.size(); n++) {
            JSONObject eapi = (JSONObject) eapis.get(n);
            JSONArray operations=(JSONArray) eapi.get("operations");
            String pathh = (String) jobj.get("path");
            JSONObject op = (JSONObject) operations.get(0);
            if(exists(operations,"httpMethod")) {
                method = (op.get("httpMethod")).toString();
            }
            else {
                method = (op.get("method")).toString();
            }

            String nickname = (op.get("nickname")).toString();
            String desc = (op.get("nickname")).toString();
            if(exists(operations,"notes")) {
                notes = (op.get("notes")).toString();
            }
            else {
                notes=(op.get("nickname")).toString();
            }

            if(exists(operations,"summary")) {
                summary = (op.get("summary")).toString();
            }
            else {
                summary=(op.get("nickname")).toString();
            }

            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            JSONArray param = (JSONArray) op.get("parameters");
            String parameters = gson.toJson(param);
            JSONArray res = (JSONArray) op.get("responseMessages");
            String response = gson.toJson(res);


            requests.add(new Request(path, desc, method, notes, nickname, summary, parameters, response));
        }
            }
    }

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

            // Create Root Pane.
            VBox vroot = new VBox();
            vroot.setPadding(new Insets(20, 10, 10, 10));
            CheckBox selectall = new CheckBox("SELECT ALL");
            TextField textField = new TextField();
            textField.setPromptText("Search here!");
            textField.setOnKeyReleased(keyEvent ->
            {

            });
            BorderPane bPane1 = new BorderPane();
            bPane1.setPrefWidth(550);
            bPane1.setLeft(selectall);
            bPane1.setRight(textField);
            vroot.getChildren().add(bPane1);
            selectall.selectedProperty().addListener((obs, wasSelected, isNowSelected)->{
                if (isNowSelected) {
                    selectedRequests.addAll(requests);
                }
                else {
                    selectedRequests.clear();
                }

            });

            for (Request req: requests) {

                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.getPath() + " : " + req.getDesc());
                TitledPane firstTitledPane = new TitledPane();
                BorderPane bPane = new BorderPane();
                bPane.setPrefWidth(550);
                bPane.setLeft(chk);
                firstTitledPane.setGraphic(bPane);
                VBox content1 = new VBox();
                content1.setMinHeight(Region.USE_PREF_SIZE);
                        content1.getChildren().add(new Label("nickname : "+req.getNickname()));
                        content1.getChildren().add(new Label("Summary : "+req.getSummary()));
                        content1.getChildren().add(new Label("Parameters : "+req.getParameters()));
                        content1.getChildren().add(new Label("Response Messages : "+req.getResponse()));
                        firstTitledPane.setContent(content1);
                        firstTitledPane.setExpanded(false);
                        vroot.getChildren().addAll(firstTitledPane);

            }

            ScrollPane scrollPane = new ScrollPane();
            scrollPane.setFitToHeight(true);
            scrollPane.setFitToWidth(true);
            Button terminer = new Button("Terminer");
            terminer.setAlignment(Pos.BASELINE_CENTER);
            vroot.getChildren().addAll(terminer);
            vroot.setSpacing(10);
            scrollPane.setContent(vroot);
            Scene scene = new Scene(scrollPane, 620, 400);
            stage.setScene(scene);
            stage.show();
        }



    private static String getUrlContents(String theUrl) {
        StringBuilder content = new StringBuilder();

        // many of these calls can throw exceptions, so i've just
        // wrapped them all in one try/catch statement.
        try {
            // create a url object
            URL url = new URL(theUrl);

            // create a urlconnection object
            URLConnection urlConnection = url.openConnection();

            // wrap the urlconnection in a bufferedreader
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            String line;

            // read from the urlconnection via the bufferedreader
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
    private static boolean exists(JSONArray jsonArray, String value){
        return jsonArray.toString().contains(value);
    }
    public static void main(String[] args) {
        Application.launch(args);
        }}

, а вот класс запроса:

    import java.util.Objects;
public class Request {

    private final String path ;
    private final String desc ;
    private final String method ;
    private final String notes ; 
   // private final String type ;
    private final String nickname ;
    private final String summary ;
    private final String parameters ;
    private final String response ;
    public Request(String path, String desc, String method, String notes, String nickname, String summary, String parameters, String response) {
        super();
        this.path=path ;
        this.desc=desc ;
        this.method=method ;
        this.notes=notes ;
        this.nickname=nickname ;
        this.summary=summary ;
        this.parameters=parameters ;
        this.response=response ;
    }

    public String getPath() {
        return path;
    }
    public String getDesc() {
        return desc;
    }
    public String getMethod() {
        return method;
    }

    public String getNotes() {
        return notes;
    }

    /*public String getType() {
        return type;
    }*/

    public String getNickname() {
        return nickname;
    }

    public String getSummary() {
        return summary;
    }

    public String getParameters() {
        return parameters;
    }

    public String getResponse() {
        return response;
    }

    @Override
    public int hashCode() {
        return Objects.hash(path, desc, method, notes, nickname, summary, parameters, response);
    }

    @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(path, other.path) &&
                Objects.equals(desc, other.desc) &&
                Objects.equals(method, other.method) &&
                Objects.equals(notes, other.notes)&&
                //Objects.equals(type, other.type)&&
                Objects.equals(nickname, other.nickname)&&
                Objects.equals(summary, other.summary)&&
                Objects.equals(parameters, other.parameters)&&
                Objects.equals(response, other.response);
    }


}

enter code here

1 Ответ

3 голосов
/ 27 апреля 2020

Если вам не нужно использовать ObservableSet, попробуйте этот маршрут. Используйте HashSet и ObservableList. Код ниже.

import java.util.HashSet;
import java.util.Set;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class App extends Application
{

    private TableView<Person> table = new TableView();
    Set<Person> hashSet = new HashSet();    
    private ObservableList<Person> data;

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

    @Override
    public void start(Stage stage)
    {
        hashSet.add(new Person("Jacob", "Smith", "jacob.smith@example.com"));
        hashSet.add(new Person("Isabella", "Johnson", "isabella.johnson@example.com"));        
        hashSet.add(new Person("Ethan", "Williams", "ethan.williams@example.com"));
        hashSet.add(new Person("Emma", "Jones", "emma.jones@example.com"));
        hashSet.add(new Person("Michael", "Brown", "michael.brown@example.com"));

        data = FXCollections.observableArrayList(hashSet);

        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(450);
        stage.setHeight(550);

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));

        table.setEditable(true);

        TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(
                new PropertyValueFactory<Person, String>("firstName"));

        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(
                new PropertyValueFactory<Person, String>("lastName"));

        TableColumn emailCol = new TableColumn("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(
                new PropertyValueFactory<Person, String>("email"));

        FilteredList<Person> flPerson = new FilteredList(data, p -> true);//Pass the data to a filtered list
        table.setItems(flPerson);//Set the table's items using the filtered list
        table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);

        //Adding ChoiceBox and TextField here!
        ChoiceBox<String> choiceBox = new ChoiceBox();
        choiceBox.getItems().addAll("First Name", "Last Name", "Email");
        choiceBox.setValue("First Name");

        TextField textField = new TextField();
        textField.setPromptText("Search here!");
        textField.setOnKeyReleased(keyEvent ->
        {
            switch (choiceBox.getValue())//Switch on choiceBox value
            {
                case "First Name":
                    flPerson.setPredicate(p -> p.getFirstName().toLowerCase().contains(textField.getText().toLowerCase().trim()));//filter table by first name
                    break;
                case "Last Name":
                    flPerson.setPredicate(p -> p.getLastName().toLowerCase().contains(textField.getText().toLowerCase().trim()));//filter table by first name
                    break;
                case "Email":
                    flPerson.setPredicate(p -> p.getEmail().toLowerCase().contains(textField.getText().toLowerCase().trim()));//filter table by first name
                    break;
            }
        });

        choiceBox.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) ->
        {//reset table and textfield when new choice is selected
            if (newVal != null)
            {
                textField.setText("");
                flPerson.setPredicate(null);//This is same as saying flPerson.setPredicate(p->true);
            }
        });
        HBox hBox = new HBox(choiceBox, textField);//Add choiceBox and textField to hBox
        hBox.setAlignment(Pos.CENTER);//Center HBox
        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(label, table, hBox);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }

    public static class Person
    {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

        private Person(String fName, String lName, String email)
        {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
            this.email = new SimpleStringProperty(email);
        }

        public String getFirstName()
        {
            return firstName.get();
        }

        public void setFirstName(String fName)
        {
            firstName.set(fName);
        }

        public String getLastName()
        {
            return lastName.get();
        }

        public void setLastName(String fName)
        {
            lastName.set(fName);
        }

        public String getEmail()
        {
            return email.get();
        }

        public void setEmail(String fName)
        {
            email.set(fName);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...