如何将编辑后的 JTable 数据保存到数据库?
首先对我糟糕的英语感到抱歉.我会尽力了解你我的问题.
只要点击保存"按钮,我只想保存用户在 JTable 中输入的新数据.
我正在从数据库的前两列中检索学生 ID、姓名,并且我在第三列中添加了当前日期,并且在第四列中添加了缺席/存在作为可编辑的第四列.我有以下代码从数据库中检索数据.
I am retrieving Student ID, Name in first two columns from database and also i have added current date in third column and Absent/Present as fourth column which is editable. I have following code to retrieve data from database.
**Attendance.java** :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Vector;
/**
*
* @author Admin
*/
public class Attendance{
Connection con = Connectdatabase.ConnecrDb();
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
String d1 = fromUser.format(sqlDate);
String d = d1.toString();
public Vector getEmployee()throws Exception
{
Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();
PreparedStatement pre = con.prepareStatement("select studentid,name from student");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> employee = new Vector<String>();
employee.add(rs.getString(1)); //Empid
employee.add(rs.getString(2));//name
employee.add(d);
employeeVector.add(employee);
}
if(con!=null)
con.close();
rs.close();
pre.close();
return employeeVector;
}
}
**AttendanceGUI.java : **
**AttendanceGUI.java : **
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.sql.Connection;
import java.util.Vector;
import javax.swing.JOptionPane;
/**
*
* @author Admin
*/
public class AttendanceGUI extends javax.swing.JFrame {
/**
* Creates new form AttendanceGUI
*/
Connection con = Connectdatabase.ConnecrDb();
private Vector<Vector<String>> data;
private Vector<String> header;
public AttendanceGUI() throws Exception {
this.setLocationRelativeTo(null);
setExtendedState(MAXIMIZED_BOTH);
Attendance att = new Attendance();
data = att.getEmployee();
header = new Vector<String>();
header.add("Student ID");
header.add("Student Name");
header.add("Date");
header.add("Absent/Present");
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
AttendanceT = new javax.swing.JTable();
SaveAtt = new javax.swing.JButton();
Exit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
AttendanceT.setModel(new javax.swing.table.DefaultTableModel(
data,header
)
{public boolean isCellEditable(int row, int column){return true;}}
);
AttendanceT.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(AttendanceT);
tca.adjustColumns();
AttendanceT.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jScrollPane1.setViewportView(AttendanceT);
SaveAtt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/save.png"))); // NOI18N
SaveAtt.setText("Save Attendance");
SaveAtt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveAttActionPerformed(evt);
}
});
Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exit.png"))); // NOI18N
Exit.setText("Exit");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(176, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void SaveAttActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try{
new AttendanceGUI().setVisible(true);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JTable AttendanceT;
private javax.swing.JButton Exit;
private javax.swing.JButton SaveAtt;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
我在运行 JFrame 时得到的输出:
This output I get when I run JFrame :
现在,我真正想要的是每当用户将数据编辑到 JTable 中,就像下图一样:
****点击保存考勤按钮后,当前的 JTable 值应输入到数据库中.我正在使用 Firefox 中的插件 Sqlite 数据库.我在我的数据库中创建了出勤表,该表具有 studentid 整数、名称 varchar、日期 DATETIME 和 preab VARCHAR(用于存储特定学生是否存在)****
****After clicking Save Attendance button the current JTable values should entered into the database. I am using Sqlite database which is addon in Firefox. I have created attendance table in my database which is having studentid integer, name varchar, date DATETIME, and preab VARCHAR(This to store whether particular student was present or absent) ****
我希望你能明白我的问题所在.提前致谢.
I hope that you get what my problem is. Thanks in advance.
推荐答案
当您使用 DefaultTableModel
时,您必须向该模型注册一个侦听器,一个 TableModelListener
侦听更改.如何使用 TableModelListener
As you are using DefaultTableModel
you have to register a listener to that model a TableModelListener
listening for changes. How to use TableModelListener
例子:
myTable.getModel().addTableModelListener(new TableModelListener(){
@Override
public void tableChanged(TableModelEvent evt){
//code here
}
});
相关文章