gpt4 book ai didi

java - getValueAt() 将数据库中的条目加倍

转载 作者:行者123 更新时间:2023-11-29 11:32:05 24 4
gpt4 key购买 nike

我编写了一个小程序,它使用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();
}
}
});

除了每行被放入数据库两次之外,一切正常。例如,如果我选择第三行,我会在数据库中获得两次。在我看来,按下鼠标时它会生成一个条目,释放时会生成一个条目,当我使用键盘箭头时它不会出现。谁能帮我吗?

最佳答案

请使用以下逻辑

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));
}
}
});

我看了这篇文章java-listselectionlistener-interface-with-keyboard

关于java - getValueAt() 将数据库中的条目加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com