0

用户已经连续选择了一个字段的值,我如何获得所选行中的 id 字段的值?比如用户选择第2行name字段的值,我想了解第2行id字段的值。TableModelListener应该怎么写?

public class Main {
    public static DefaultTableModel model;

    public static void main(String[] args) throws Exception {
        model = new DefaultTableModel();
        JFrame frame = new JFrame("Creating a Scrollable JTable!");
        JPanel panel = new JPanel();
        model.addColumn("id");
        model.addColumn("name");
        model.addColumn("family");
        Class.forName("oracle.jdbc.driver.OracleDriver");
        java.sql.Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "SYSTEM", "1234");
        PreparedStatement st = con.prepareStatement("select * from person");
        ResultSet r = st.executeQuery();
        while (r.next()) {
            model.addRow(new Object[]{r.getString("id"), r.getString("name"), r.getString("family")});
        }
        st.close();
        con.close();
        model.addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                System.out.println(model.getValueAt(e.getFirstRow(), e.getColumn()));
            }
        });
        JTable table = new JTable(model);
        frame.add(panel);
        panel.add(table);
        frame.setVisible(true);
    }
}
4

2 回答 2

2

使用 ListSelectionListener 而不是 TableModelListener:

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) return;
            int selectedRow = table.convertRowIndexToModel(table.getSelectedRow());
            int selectedColumn = table.convertColumnIndexToModel(0);

            String selectedId = (String)model.getValueAt(selectedRow, selectedColumn);
            System.out.println(selectedId);
        }
    });
于 2012-07-28T12:08:56.660 回答
1

当 id 列索引为 0 时: System.out.println(model.getValueAt(e.getFirstRow(),0))

于 2012-07-28T12:07:06.700 回答