用户已选择一行中的字段值,如何获取所选行中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);
}
}
答案 0 :(得分: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);
}
});
答案 1 :(得分:1)
当id列索引为0时:System.out.println(model.getValueAt(e.getFirstRow(),0))