用户已经连续选择了一个字段的值,我如何获得所选行中的 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);
}
}