You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为ListView的每个ListCell添加监听器以获取单元格数据并调用方法

JavaFX ListView点击获取单元格数据实现方案

现有代码问题修正

首先你当前的代码有两处可调整的基础问题:

  • FXML中ListView的onMouseClicked绑定了#loadData,会导致每次点击列表都重新加载全量数据,需要修改为自定义的点击处理方法
  • 控制器中conn字段标注了@FXML,静态属性无法被FXML注入,需要移除该注解

方案1:保持现有数据结构直接实现(改动最小)

步骤1:修改FXML

把ListView的配置改为:

<ListView fx:id="OrgTbl2" layoutX="7.0" layoutY="6.0" prefHeight="987.0" prefWidth="958.0" />

去掉错误的onMouseClicked绑定。

步骤2:控制器添加选中监听器

在initialize方法的loadData()调用后添加选中监听逻辑:

public void initialize (URL url, ResourceBundle resourceBundle) throws SQLException, ClassNotFoundException {
    loadData();
    // 添加列表项选中监听
    OrgTbl2.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
        if (newVal == null) return;
        // 你查询的字段顺序为CustomerName(索引0)、CustomerID(索引1)、Inactive(索引2)
        String customerId = newVal.get(1).toString();
        String customerName = newVal.get(0).toString();
        boolean isInactive = Boolean.parseBoolean(newVal.get(2).toString());
        // 此处调用你自己实现的客户详情展示方法即可
        yourCustomShowDetailMethod(customerId, customerName, isInactive);
    });
}

方案2:优化为直接绑定orgmodel(更易维护)

你已经在加载数据时构造了orgmodel对象的列表,直接绑定该列表到ListView会更方便,不需要按索引取字段,避免顺序出错:

步骤1:修改ListView泛型

把控制器中ListView的声明改为:

@FXML
private ListView<orgmodel> OrgTbl2;

步骤2:修改loadData方法的赋值逻辑

把原来的OrgTbl2.setItems(data);改为:

// 先设置CellFactory指定列表项显示的内容(这里显示客户名称,可自定义)
OrgTbl2.setCellFactory(param -> new ListCell<orgmodel>() {
    @Override
    protected void updateItem(orgmodel item, boolean empty) {
        super.updateItem(item, empty);
        setText(empty || item == null ? null : item.getCustomerName());
    }
});
// 直接绑定orgmodel列表
OrgTbl2.setItems(OrganizationObservableList);

步骤3:选中监听直接拿orgmodel对象

OrgTbl2.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
    if (newVal != null) {
        // 直接拿orgmodel的属性,不需要按索引取,更安全
        String customerId = newVal.getCustomerId();
        // 调用你的详情展示方法
        yourCustomShowDetailMethod(newVal);
    }
});

注:需要确保你的orgmodel类已经实现了对应属性的getter方法。


内容的提问来源于stack exchange,提问作者Wackyvert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:15:08