
本教程详细介绍了如何在javafx应用程序中实现`tableview`的数据过滤功能。通过结合`textfield`进行实时搜索,并利用`filteredlist`动态更新表格内容。重点阐述了如何在用户点击按钮后,从已过滤的`tableview`中准确获取当前显示的数据,并进一步处理,例如传递给其他fxml视图。
在JavaFX应用开发中,TableView是展示数据集合的强大组件。当数据量较大时,为用户提供过滤功能以快速定位所需信息变得尤为重要。本教程将引导您完成构建一个带有搜索过滤功能并能在按钮点击后获取当前过滤结果的TableView。
首先,我们需要在FXML文件中定义TableView、用于输入的TextField和触发搜索操作的Button。
以下是一个典型的FXML布局片段,包含了这些组件:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="your.package.name.Controller">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
<children>
<HBox alignment="CENTER_LEFT" spacing="10.0" GridPane.rowIndex="0">
<TextField fx:id="mTextField" prefHeight="28.0" prefWidth="366.0" promptText="输入ID搜索..." />
<Button fx:id="searchBtn" mnemonicParsing="false" onAction="#handleSearch" prefHeight="26.0" prefWidth="166.0" text="Search" />
</HBox>
<TableView fx:id="mTableView" 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>
</children>
</GridPane>在控制器中,我们需要注入FXML组件,并准备数据模型。假设我们有一个Employee类,包含id、name和salary属性。
立即学习“Java免费学习笔记(深入)”;
package your.package.name;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import java.util.List;
import java.util.stream.Collectors;
public class Controller {
@FXML
private TableView<Employee> mTableView;
@FXML
private TableColumn<Employee, Integer> idColumn;
@FXML
private TableColumn<Employee, String> nameColumn;
@FXML
private TableColumn<Employee, String> salColumn;
@FXML
private TextField mTextField;
@FXML
private Button searchBtn; // 注入Search按钮,虽然本例中直接使用onAction
// 存储所有原始数据的列表
private ObservableList<Employee> mList = FXCollections.observableArrayList();
/**
* Employee 数据模型示例
*/
public static class Employee {
private final int id;
private final String name;
private final String salary; // 假设salary为String类型
public Employee(int id, String name, String salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
// Getter 方法 (PropertyValueFactory 需要这些方法)
public int getId() { return id; }
public String getName() { return name; }
public String getSalary() { return salary; }
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", salary='" + salary + '\'' +
'}';
}
}
/**
* 在控制器初始化时调用,用于设置TableView和过滤逻辑。
*/
@FXML
public void initialize() {
// 1. 设置列的CellValueFactory,将Employee对象的属性映射到TableView的列
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
salColumn.setCellValueFactory(new PropertyValueFactory<>("salary"));
// 2. 加载原始数据
loadRecords();
// 3. 初始化FilteredList,用于实现过滤功能
// 初始时显示所有数据 (b -> true)
FilteredList<Employee> filteredList = new FilteredList<>(mList, b -> true);
// 4. 监听mTextField的文本变化,实时更新过滤条件
mTextField.textProperty().addListener((observable, oldValue, newValue) -> {
filteredList.setPredicate(employee -> {
// 如果搜索框为空或空白,则显示所有数据
if (newValue == null || newValue.isBlank()) {
return true;
}
String searchKeyword = newValue.toLowerCase();
// 示例过滤逻辑:根据员工ID进行匹配
// 您可以扩展此逻辑以匹配姓名、薪资或其他字段
if (String.valueOf(employee.getId()).toLowerCase().contains(searchKeyword)) {
return true;
}
// 更多过滤条件示例:
// if (employee.getName().toLowerCase().contains(searchKeyword)) { return true; }
// if (employee.getSalary().toLowerCase().contains(searchKeyword)) { return true; }
return false; // 不匹配任何条件
});
});
// 5. 使用SortedList包装FilteredList,以支持TableView的排序功能
SortedList<Employee> sortedList = new SortedList<>(filteredList);
// 将SortedList的比较器属性绑定到TableView的比较器属性,以便TableView的排序功能生效
sortedList.comparatorProperty().bind(mTableView.comparatorProperty());
// 6. 将最终的SortedList(包含过滤和排序逻辑)设置给TableView
mTableView.setItems(sortedList);
}
/**
* 模拟从数据库或其他源加载数据。
*/
private void loadRecords() {
// 示例数据
mList.addAll(
new Employee(101, "Alice Smith", "50000"),
new Employee(102, "Bob Johnson", "60000"),
new Employee(103, "Charlie Brown", "55000"),
new Employee(201, "David Lee", "70000"),
new Employee(202, "Eve Davis", "62000"),
new Employee(301, "Frank White", "48000")
);
}
}当用户点击“Search”按钮时,我们通常需要获取当前TableView中显示的数据(即经过过滤后的结果),以便进行进一步的操作,例如加载另一个FXML视图并传递这些数据。
TableView的getItems()方法返回的是当前显示在表格中的ObservableList。当TableView绑定到一个SortedList(它又包装了FilteredList)时,getItems()将返回经过过滤和排序后的数据。
// 承接上面的Controller类
// ...
/**
* 处理Search按钮点击事件。
* 在此方法中获取当前TableView中显示的(已过滤)数据。
*/
@FXML
public void handleSearch(ActionEvent event) {
// 获取当前TableView中显示的所有项,这些项已经经过TextField的过滤逻辑处理
ObservableList<Employee> currentDisplayedItems = mTableView.getItems();
if (!currentDisplayedItems.isEmpty()) {
System.out.println("--- 搜索按钮点击,获取当前过滤结果 ---");
// 示例:遍历并打印所有过滤结果
currentDisplayedItems.forEach(employee -> System.out.println("匹配员工: " + employee));
// 示例:获取第一个匹配项。这在预期只有一个结果时非常有用。
Employee firstMatchedEmployee = currentDisplayedItems.get(0);
System.out.println("第一个匹配的员工: " + firstMatchedEmployee.getName() + " (ID: " + firstMatchedEmployee.getId() + ")");
// 进一步处理逻辑:
// 1. 如果预期只有一个结果,并且需要将其传递给另一个FXML视图:
// FXMLLoader loader = new FXMLLoader(getClass().getResource("AnotherView.fxml"));
// Parent root = loader.load();
// AnotherController anotherController = loader.getController();
// anotherController.initData(firstMatchedEmployee); // 假设AnotherController有一个initData方法
// Stage stage = new Stage();
// stage.setScene(new Scene(root));
// stage.show();
// ((Node)(event.getSource())).getScene().getWindow().hide(); // 关闭当前窗口
// 2. 如果搜索结果可能包含多个项,并且需要用户从中选择一个,或者需要对所有结果进行批量处理:
if (currentDisplayedItems.size() > 1) {
System.out.println("提示:搜索结果包含多个匹配项。您可以选择进一步处理所有项或提示用户选择。");
// 例如,可以将这些结果显示在一个新的对话框中供用户选择
}
} else {
System.out.println("没有找到匹配的员工。");
// 可以向用户显示一个警告或提示信息
}
}
}以上就是JavaFX TableView:实现数据过滤与按钮点击后的选中值获取的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号