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

Java: 如何让监听器点击表格行时获取指定列的ID数据?

解决方案

你已经拿到了选中的视图行号,只需要将行号转换为TableModel对应的实际行号,再从模型中取出ID列对应的值即可,调整后代码如下:

// 调整后的监听器实现
ListSelectionModel model = NPC_Table.getSelectionModel();
model.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        if(!model.isSelectionEmpty() && !e.getValueIsAdjusting()) {
            // 拿到选中的视图行号
            int selectedViewRow = model.getMinSelectionIndex();
            // 转换为模型行号,避免表格排序、列拖动后数据错位
            int selectedModelRow = NPC_Table.convertRowIndexToModel(selectedViewRow);
            // 请将idColumnIndex替换为ID列在你的TableModel中的实际索引,索引从0开始计数
            int idColumnIndex = 0;
            // 取出ID值,根据你的ID实际类型强转,比如Integer、String
            Object idObj = NPC_Table.getModel().getValueAt(selectedModelRow, idColumnIndex);
            Integer id = (Integer) idObj; // 如果ID是字符串类型就改为String id = (String) idObj
            // 此处可使用拿到的id执行后续业务逻辑
        }
    }
});
  • 新增!e.getValueIsAdjusting()判断是为了避免选中过程中多次触发事件,仅在选中完成后执行逻辑,减少冗余调用
  • 如果你的ID列在表格视图中展示、未做隐藏,也可以直接用NPC_Table.getValueAt(selectedViewRow, 视图列索引)取值,但如果允许用户拖动调整列顺序,通过模型索引取值稳定性更高
  • 如果ID是隐藏列(仅存在于TableModel中,不在表格界面展示),必须通过getModel()取值,不能直接通过JTable对象取值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 03:54:05