i am new to Java FX and trying to implement a table view with filter using a textfield. i have a textfield and search button along with it. my requirement is i will enter a search value in textfield and click the search button. if the value is in the table i need to load another fxml(passing the selected value as an argument to that fxml and controller).But i am unable to get the filtered value to handleSearch() method.
FXML File(TableView textField and Button)
<TableView fx:id="mTableView" layoutY="71.0" prefHeight="451.0" prefWidth="929.0" GridPane.rowIndex="1">
<columns>
<TableColumn fx:id="idColumn" prefWidth="75.0" text="ID" />
<TableColumn fx:id="nameColumn" prefWidth="75.0" text="Name" />
<TableColumn fx:id="salColumn" prefWidth="75.0" text="Salary" />
</columns>
</TableView>
....
....
<TextField fx:id="mTextField" prefHeight="28.0" prefWidth="366.0" />
<Button fx:id="searchBtn" mnemonicParsing="false" onAction="#handleSearch" prefHeight="26.0" prefWidth="166.0" text="Search" />
..
Controller
@FXML
private TableView<Employee> mTableView;
@FXML
private TableColumn<Employee, Integer> idColumn;
@FXML
private TableColumn<Employee, String> nameColumn;
@FXML
private TableColumn<Employee, String> salColumn;
ObservableList<Employee> mList = FXCollections.observableArrayList();
@FXML
public void handleSearch(ActionEvent event) {
// need to get selected value here to load another fxml
}
public void loadRecords(){
//this method is called to populate the tableview with data from DB( called from initialize() method of the controller)
...
...
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
nameColumn.setCellValueFactory(new PropertyValueFactory<>("Name"));
salColumn.setCellValueFactory(new PropertyValueFactory<>("salary"));
mTableView.setItems(mList);
FilteredList<Employee> filteredList = new FilteredList<>(mList,b->true);
mTextField.textProperty().addListener(((observableValue, oldValue, newValue) -> {
key = null;
filteredList.setPredicate(cinema -> {
if(newValue.isEmpty() || newValue.isBlank() || newValue == null){
return true;
}
String searchKeyword = newValue.toLowerCase();
if(isContain(cinema.getId().toString().toLowerCase(),searchKeyword)){
return true;
}
else {
return false;
}
});
}));
SortedList<Employee> sortedList = new SortedList<>(filteredList);
key = filteredList.get(0).getId().toString();
sortedList.comparatorProperty().bind(mTableView.comparatorProperty());
mTableView.setItems(sortedList);
}
Get the list from the table when you need it:
@FXML
public void handleSearch(ActionEvent event) {
List<Employee> employees = mTableView.getItems();
if (! employees.isEmpty()) {
// get first item:
Employee firstSearchResults = employees.get(0);
// now do whatever you need
// You may want special handling if there is more than one result, etc.
}
}