You need to enable JavaScript to run this app. 如何通过ListSelectionModel获取JTable选中行的指定单元格值?
优惠活动
大模型
产品
解决方案
定价
更多

如何通过ListSelectionModel获取JTable选中行的指定单元格值?

获取JTable选中行的Item ID值用于MySQL更新

你已经实现了行选中并获取索引的功能,接下来只需利用选中行索引结合列索引(Item ID是第0列),就能拿到对应单元格的值,用于后续数据库更新操作。

两种获取Item ID的方式

1. 直接从JTable视图获取

JTable的getValueAt(int row, int column)方法可以直接返回指定单元格的值,因为Item ID是第一列,列索引为0:

// 在选中事件或删除按钮事件中获取
if (selectedRow != -1) {
    String itemId = (String) loanedItemsTable.getValueAt(selectedRow, 0);
    System.out.println("选中的Item ID: " + itemId);
    // 这里写更新MySQL的逻辑,比如用JDBC执行DELETE或UPDATE语句
}

2. 从DefaultTableModel数据模型获取(推荐)

DefaultTableModel是表格的数据来源,直接从模型取值更符合MVC思想,避免视图和数据耦合:

if (selectedRow != -1) {
    String itemId = (String) model.getValueAt(selectedRow, 0);
    System.out.println("选中的Item ID: " + itemId);
    // 执行数据库操作
}

整合到你的代码示例(添加删除按钮)

给你的代码增加一个删除按钮,在按钮点击事件中获取Item ID并处理:

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class App {

    private static JTable loanedItemsTable;
    private static JScrollPane tableScroll;
    private static DefaultTableModel model;
    private static int selectedRow = -1; // 初始化为-1表示无选中行

    public static void main(String[] args) throws Exception {

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();

        frame.setSize(800,600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("table");
        frame.setResizable(false);
        
        panel.setLayout(null);
        panel.setBackground(Color.gray);
        
        frame.add(panel);
        
        // 表格列定义
        String loanTableColumns [] = {
            "item ID",
            "Item Loaned",
            "Loan Start Date",
            "Return Date",
            "State",
            "Fee to pay",
            "Customer Name"
        };

        // 补全每行数据(需对应所有列)
        String loanTableData [] [] = {
            {"1", "Laptop", "2024-01-01", "2024-01-10", "Loaned", "0", "John Doe"},
            {"2", "Projector", "2024-01-05", "2024-01-15", "Loaned", "0", "Jane Smith"}
        };

        model = new DefaultTableModel(loanTableData, loanTableColumns);
        
        loanedItemsTable = new JTable(model){
            public boolean editCellAt(int row, int column, java.util.EventObject e) {
                return false;
            }
        };

        tableScroll = new JScrollPane(loanedItemsTable);
        tableScroll.setBounds(30, 60, 740, 400);
        panel.add(tableScroll);

        // 行选中监听
        loanedItemsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) { // 避免重复触发事件
                    selectedRow = loanedItemsTable.getSelectedRow();
                    if (selectedRow != -1) {
                        System.out.println("选中行索引: " + selectedRow);
                    }
                }
            }
        });

        // 添加删除按钮
        JButton deleteBtn = new JButton("删除选中行");
        deleteBtn.setBounds(30, 480, 150, 30);
        panel.add(deleteBtn);

        // 按钮点击事件
        deleteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (selectedRow != -1) {
                    // 获取Item ID
                    String itemId = (String) model.getValueAt(selectedRow, 0);
                    
                    // 1. 执行MySQL更新/删除操作(需自行配置JDBC连接)
                    // String sql = "DELETE FROM loaned_items WHERE item_id = ?";
                    // try (Connection conn = DriverManager.getConnection(url, user, pass);
                    //      PreparedStatement pstmt = conn.prepareStatement(sql)) {
                    //     pstmt.setString(1, itemId);
                    //     pstmt.executeUpdate();
                    // } catch (SQLException ex) {
                    //     ex.printStackTrace();
                    // }

                    // 2. 删除表格中的行
                    model.removeRow(selectedRow);
                    selectedRow = -1;
                    JOptionPane.showMessageDialog(frame, "已删除Item ID: " + itemId + "的记录");
                } else {
                    JOptionPane.showMessageDialog(frame, "请先选中要删除的行");
                }
            }
        });

        frame.setVisible(true);
    }
}

注意事项

  • 初始化selectedRow为-1,用来判断是否有选中行,避免空指针异常。
  • 在列表选择监听中加入!e.getValueIsAdjusting(),可避免选中行时多次触发事件。
  • 数据库操作建议使用PreparedStatement防止SQL注入,确保安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:53:18