4

まず、私の下手な英語で申し訳ありません。私の問題を理解するために最善を尽くします。

私が望むのは、[保存] ボタンがクリックされるたびに、ユーザーが JTable に入力した新しいデータを保存することだけです。

データベースから最初の 2 列に学生 ID、名前を取得しています。また、3 列目に現在の日付を追加し、編集可能な 4 列目に不在/出席を追加しました。データベースからデータを取得するための次のコードがあります。

**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 : **

/*
 * 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 に編集するときです:

ここに画像の説明を入力

****[出席の保存] ボタンをクリックすると、現在の JTable 値がデータベースに入力されます。FirefoxのアドオンであるSqliteデータベースを使用しています。データベースに出席テーブルを作成しました。このテーブルには、studentid integer、name varchar、date DATETIME、preab VARCHAR (特定の学生が出席したか欠席したかを保存するため) **** があります。

私の問題が何であるかを理解していただければ幸いです。前もって感謝します。

4

2 に答える 2

0
     public void happi(String name, String age, String id){
//this method should be located on a class, then you just instantiate the class in the main form
String query=null;
try{

           query = "update tbltest set name = '"+name+"',age = '"+age+"' where id = '"+id+"'";
           stmt.executeUpdate(query);


       }
       catch(Exception ex){JOptionPane.showMessageDialog(null,""+ex);}
       finally{
           super.closeConnection(connect);
           super.closeStatement(stmt);

       }

}//end of happi

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    //a button with event ActionPerformed (save button)
   table.updateUI();

}//end

private void tablePropertyChange(java.beans.PropertyChangeEvent evt) {                                     
    // a JTablenamed"table"
    try{
    int row = table.getSelectedRow();
    int column = table.getSelectedColumn();
    int c = table.getColumnCount();

     DBHandler dbh = new DBHandler();
     dbh.happi((table.getModel().getValueAt(row, 0).toString()),     (table.getModel().getValueAt(row, 1).toString()), (table.getModel().getValueAt(row, 2).toString()));

    }catch(Exception e){}
} '
于 2014-09-03T17:30:10.087 に答える