我编写了一个使用JTable的小程序(在本例中为t1)并实现了ListSelectionListener,因此通过单击一行,其中的数据将被放入数据库中(我使用mysql并通过JDBC连接)。
// t1 is a JTable
t1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
t1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int row = t1.getSelectedRow();
try {
String sql = "INSERT INTO xxx (x1, x2, x3) VALUES(?,?,?)";
PreparedStatement pst = conn.prepareStatement(sql);
int col1 = (int)t1.getValueAt(row, 0);
int col2 = (int)t1.getValueAt(row, 1);
int col3 = (int)t1.getValueAt(row, 2);
pst.setLong(1, col1);
pst.setLong(2, col2);
pst.setLong(3, col3);
pst.addBatch();
pst.executeBatch();
}
catch (SQLException e1) {
e1.printStackTrace();
}
}
});
除了将每行放入数据库两次外,一切正常。例如,如果我选择第三行,我在数据库中得到它两次。在我看来,它在按下鼠标时会输入一个,在释放时会输入一个,当我使用键盘箭头时它不会出现。任何人都可以帮助我吗?
答案 0 :(得分:1)
请使用以下逻辑
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if ( e.getValueIsAdjusting() ){
return;
}
if (e.getSource() == table.getSelectionModel() &&
table.getRowSelectionAllowed() ) {
int selected = table.getSelectedRow();
System.out.println("Column 1 : " + table.getValueAt(selected, 0));
System.out.println("Column 2 : " + table.getValueAt(selected, 1));
System.out.println("Column 3 : " + table.getValueAt(selected, 2));
}
}
});