为什么我的 jTable 中的值会覆盖第一个值 从 jcombobox 中选择?有人可以帮我解决这个代码吗:
private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Connection con;
Statement stmt;
try {
// TODO add your handling code here
Class.forName("sun.jdbc.odbc.JdbcOdbc");
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex);
}
try {
con= DriverManager.getConnection("Jdbc:Odbc:food");
stmt= con.createStatement();
int row = 0;
String st= JcbSub.getSelectedItem().toString();
jTable3.setValueAt(st, row, 0);
row ++;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
最佳答案
尽管您在最后增加了行号,但您已将其声明为局部变量 它会丢失其值并初始化为 0 在每个方法调用时。因此,您的第一行每次都会被覆盖。
int row = 0; // move this out to a member variable
String st= JcbSub.getSelectedItem().toString();
jTable3.setValueAt(st, row, 0);
row ++; // this increment currently has no effect on next method call
您每次都会打开一个新的数据库连接,而不是通过调用 con.close()
来关闭它。事实上,由于您没有通过 Statement
对象 stmt 执行任何查询,因此不需要方法内的所有 JDBC 代码。
关于java - 覆盖jTable中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16950347/