我寫了一個小例子:的JavaFX - 多個文本框應該過濾一個實現代碼如下
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Scene;
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.VBox;
import javafx.stage.Stage;
public class MultipleFilterTextfields extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
VBox vbox = new VBox();
TextField firstNameFilterTextField = new TextField();
TextField lastNameFilterTextField = new TextField();
TableView<Person> tableView = new TableView<>();
ObservableList<Person> list = FXCollections.observableArrayList(new Person("Peter", "Schmidt"),
new Person("Hans-Peter", "Schmidt"), new Person("Hans", "Mustermann"));
FilteredList<Person> filterList = new FilteredList<>(list);
tableView.setItems(filterList);
TableColumn<Person, String> firstNameCol = new TableColumn<>("FirstName");
TableColumn<Person, String> lastNameCol = new TableColumn<>("LastName");
firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
firstNameFilterTextField.textProperty().addListener((obsVal, oldValue, newValue) -> {
filterList.setPredicate(person -> person.getFirstName().contains(newValue));
});
lastNameFilterTextField.textProperty().addListener((obsVal, oldValue, newValue) -> {
filterList.setPredicate(person -> person.getLastName().contains(newValue));
});
tableView.getColumns().addAll(firstNameCol, lastNameCol);
vbox.getChildren().addAll(firstNameFilterTextField, lastNameFilterTextField, tableView);
Scene scene = new Scene(vbox, 250, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
public static void main(String[] args) {
launch(args);
}
}
它看起來像這樣:
上方tableView
有兩個TextField
S,一個過濾firstName
,另一個過濾lastName
。如果我在第一個字段中輸入:「Hans」,表格會過濾出兩個人「Hans-Peter Schmidt」和「Hans Mustermann」。如果我在第二個中輸入「Schmidt」,它將過濾「Peter Schmidt」和「Hans-Peter Schmidt」。
問題是,我無法同時對firstName
和lastName
進行過濾(使用上面的代碼)。
你有什麼想法嗎?
感謝您的幫助!