1

As the question is indecating I need a way to add a searching bar using javaFX so I tried many solutions and I found this one : https://stackoverflow.com/a/47560767/13414383 but in her case she is using a FilteredList which gave her the hand to use setPredicate methode but in my case I'm using a ObservableSet so is there is any solution to add a filter on a ObservableSet so I can add a searching bar ? Here is my code :

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

and here is the Request class :

    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
6
  • 2
    My guess is that your ObservableSet should work similarly to the ObservableList in the link you provided. FilteredList<Person> flPerson = new FilteredList(selectedRequests , p -> true);//Pass the data to a filtered list is my guess. I did not take a deep look at your code. Commented Apr 27, 2020 at 6:48
  • 1
    @Sedrick no I tried that one but it did not work ! I'm actually despirate and I think there is no solution :( Commented Apr 27, 2020 at 6:59
  • 2
    What happens if you take the linked code and change the ObservableList to ObservableSet? Commented Apr 27, 2020 at 8:01
  • 2
    minimal reproducible example please .. strip it down to the barest minimum to demonstrate what's going wrong. And please put a bit more effort into formatting the code, it's unreadable without, also: nothing related to any specific fx version (and if it would, it would be a single one not all ;) - so removed those tags. Commented Apr 27, 2020 at 8:04
  • 1
    @Sedrick it shows me : The constructor FilteredList(ObservableSet<Test2.Person>, (<no type> p) -> {}) is undefined Commented Apr 27, 2020 at 8:07

1 Answer 1

3

If you don't have to use ObservableSet, try this route. Use HashSet and ObservableList. Code Below.

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", "[email protected]"));
        hashSet.add(new Person("Isabella", "Johnson", "[email protected]"));        
        hashSet.add(new Person("Ethan", "Williams", "[email protected]"));
        hashSet.add(new Person("Emma", "Jones", "[email protected]"));
        hashSet.add(new Person("Michael", "Brown", "[email protected]"));

        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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Sedrick, I tried to use ObservableList in the code that I'm showing up but I get an error in the line : selectedRequests.addListener((Change <?extends Request> c)->chk.setSelected(selectedRequests.contains(req))); ! Since it's a whole project we can not change ObservableSet to ObservableList

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.