首先抱歉我的英语不好.我会尽力了解你的问题.我想要的只是在点击“保存”按钮时保存用户在JTable中输入的新数据.我正在从数据库的前两列中检索学生ID,名称,并且我在第三列中添加了当前日期,并且Absent / Present作...
                
首先抱歉我的英语不好.我会尽力了解你的问题.
我想要的只是在点击“保存”按钮时保存用户在JTable中输入的新数据.
我正在从数据库的前两列中检索学生ID,名称,并且我在第三列中添加了当前日期,并且Absent / Present作为可编辑的第四列.我有以下代码从数据库中检索数据.
**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;
    }
}
**出勤率GUI.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时获得的输出:
现在,我想要的是用户将数据编辑到JTable中,就像下面的图像一样:
****单击Save Attendance按钮后,当前JTable值应输入数据库.我正在使用Sqlite数据库,它是Firefox中的插件.我在我的数据库中创建了考勤表,该表具有studentid整数,名称varchar,日期DATETIME和preab VARCHAR(用于存储特定学生是否存在)****
我希望你能解决我的问题.提前致谢.
解决方法:
当您使用DefaultTableModel时,您必须向该模型注册一个监听更改的TableModelListener的监听器. How to use TableModelListener
例:
myTable.getModel().addTableModelListener(new TableModelListener(){
         @Override
         public void tableChanged(TableModelEvent evt){
             //code here
         }
});
 
本文标题为:java – 如何将已编辑的JTable数据保存到数据库?
				
        
 
            
        - plantuml画图实现代码画时序图UML用例图 2023-03-11
 - Java ServletContext与ServletConfig接口使用教程 2023-06-02
 - Java枚举学习之定义和基本特性详解 2023-04-16
 - 智能 AI 代码生成工具 Cursor 安装和使用超详细教程 2023-07-15
 - 详解springboot解决CORS跨域的三种方式 2023-02-11
 - js实现百度地图同时显示多个路书效果 2023-08-02
 - jsp 使用request为页面添加静态数据的实例 2023-07-31
 - java – HSQLDB内部:Hibernate和Integer与Long ID 2023-11-02
 - Springboot详解实现食品仓库管理系统流程 2022-12-11
 - Java @Transactional指定回滚条件 2023-04-06
 
						
						
						
						
						
				
				
				
				