Refresh Jtable

di il
5 risposte

Refresh Jtable

Ciao a tutti ho creato una Jtable che visualizza i dati in un db, ora siccome riesco a modificare i dati a cancellarli e a inserirli vorrei sapere se e possibile fare il refresjìh istantaneo dell atable senza ogni volta fare il run del programma per vedere la modifica.Se si puo fare mi indichereste qualche tutorial o qualche sito dove guardare? grazie a tutti

5 Risposte

  • Re: Refresh Jtable

    luigi83 ha scritto:


    Ciao a tutti ho creato una Jtable che visualizza i dati in un db, ora siccome riesco a modificare i dati a cancellarli e a inserirli vorrei sapere se e possibile fare il refresjìh istantaneo dell atable senza ogni volta fare il run del programma per vedere la modifica.Se si puo fare mi indichereste qualche tutorial o qualche sito dove guardare? grazie a tutti
    La domanda è vaga .... nel senso che bisogna vedere quale table model hai usato, come lo hai usato e come/quando intendi "aggiornare" i dati.
    Senza indicazioni più precise è quasi impossibile rispondere ....
  • Re: Refresh Jtable

    Quali informazioni ti servono per potermi aiutare meglio se vuoi ti posto lo script.
  • Re: Refresh Jtable

    luigi83 ha scritto:


    quali informazioni ti servono
    L'ho detto prima .... quale table model hai usato e come lo hai usato. Comunque se posti il codice (almeno quanto basta per capire l'architettura che hai usato) ... è sicuramente meglio.
  • Re: Refresh Jtable

    package gestionepiant;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JOptionPane;
    import javax.swing.table.DefaultTableModel;
    
    /**
     *
     * @author sp
     */
    public class NewJFrame1 extends javax.swing.JFrame {
        private Object con;
        Connection conn=null;
        PreparedStatement pst=null;
    
        /**
         * Creates new form NewJFrame1
         */
        @SuppressWarnings({"unchecked", "empty-statement", "unchecked", "unchecked"})
        public NewJFrame1() throws ClassNotFoundException {
            try {
                initComponents();
                Class.forName("com.mysql.jdbc.Driver");
                conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/gestionepiante","root","admin");
                Statement state =conn.createStatement();
                ResultSet rs=state.executeQuery("SELECT * FROM piante");
               
            ResultSetMetaData rsmetadata=rs.getMetaData();
            int columns=rsmetadata.getColumnCount();
           
            
            DefaultTableModel dtm= new DefaultTableModel();
            Vector columns_name=new Vector();
            Vector data_rows=new Vector();
            
            for(int i=1; i<=columns;i++)
            {
                columns_name.addElement(rsmetadata.getColumnName(i));    
            }
            
           dtm.setColumnIdentifiers(columns_name);
            
           while(rs.next()){
             data_rows=new Vector();
             for(int j=1;j<=columns;j++)
             {
                 data_rows.addElement(rs.getString(j));  
             }
             dtm.addRow(data_rows);
            }
             myTable1.setModel(dtm);
      
            } catch (SQLException ex) {
                Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
            
            
       
    
        /**
         * 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();
            myTable1 = new javax.swing.JTable();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            jLabel5 = new javax.swing.JLabel();
            jLabel6 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jTextField3 = new javax.swing.JTextField();
            jTextField4 = new javax.swing.JTextField();
            jTextField5 = new javax.swing.JTextField();
            cmd_save = new javax.swing.JButton();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jLabel7 = new javax.swing.JLabel();
            jTextField6 = new javax.swing.JTextField();
            jButton3 = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            myTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null, null},
                    {null, null, null, null, null},
                    {null, null, null, null, null},
                    {null, null, null, null, null}
                },
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4", "Title 5"
                }
            ));
            myTable1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    myTable1MouseClicked(evt);
                }
            });
            jScrollPane1.setViewportView(myTable1);
    
            jLabel1.setBackground(new java.awt.Color(255, 255, 255));
            jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
            jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jLabel1.setText("Query gestione piante");
    
            jLabel2.setText("nome_botanico");
    
            jLabel3.setText("nome_comune");
    
            jLabel4.setText("giardino");
    
            jLabel5.setText("esotica");
    
            jLabel6.setText("prezzo");
    
            jTextField2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField2ActionPerformed(evt);
                }
            });
    
            jTextField3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField3ActionPerformed(evt);
                }
            });
    
            jTextField4.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField4ActionPerformed(evt);
                }
            });
    
            cmd_save.setText("Salva");
            cmd_save.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    cmd_saveActionPerformed(evt);
                }
            });
    
            jButton1.setText("Delete");
            jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jButton1MouseClicked(evt);
                }
            });
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jButton2.setText("Cancella");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
    
            jLabel7.setText("codice_p");
    
            jButton3.setText("Update");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGap(91, 91, 91))
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(cmd_save, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(39, 39, 39)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(22, 22, 22))
                .addGroup(layout.createSequentialGroup()
                    .addGap(20, 20, 20)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addGap(18, 18, 18)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 463, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel3)
                                        .addComponent(jLabel4)
                                        .addComponent(jLabel5)
                                        .addComponent(jLabel6))
                                    .addGap(22, 22, 22)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jTextField4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)
                                        .addComponent(jTextField2)
                                        .addComponent(jTextField3)
                                        .addComponent(jTextField5))))
                            .addGap(0, 0, Short.MAX_VALUE)))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(98, 98, 98)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(60, 60, 60)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel7))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel4)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel5)
                                .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel6)
                                .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cmd_save)
                            .addComponent(jButton1)
                            .addComponent(jButton3))
                        .addComponent(jButton2))
                    .addGap(20, 20, 20))
            );
    
            pack();
        }// </editor-fold>                        
    
        private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                           
    
        private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                           
    
        private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        }                                           
    
        private void cmd_saveActionPerformed(java.awt.event.ActionEvent evt) {                                         
            try {
              String sql="Insert into piante(nome_botanico,nome_comune,giardino, esotica,prezzo) value(?,?,?,?,?)" ;
                       pst=conn.prepareStatement(sql);
            
            pst.setString(1, jTextField1.getText());
            pst.setString(2, jTextField2.getText());
            pst.setString(3, jTextField3.getText());
            pst.setString(4, jTextField4.getText());
            pst.setString(5, jTextField5.getText());
            
           pst.execute();
              JOptionPane.showMessageDialog(null,"Saved");
            }
            catch (Exception e)
            {
                JOptionPane.showMessageDialog(null,e);
        }                                        
        }
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            int p=JOptionPane.showConfirmDialog(null, "Sei sicuro di cancellare?","Delete",JOptionPane.YES_NO_OPTION);
           if(p==0){
            String sql="Delete  from piante where nome_botanico=? ";
            try{
            pst=conn.prepareStatement(sql);
            pst.setString(1,jTextField1.getText());
            pst.execute();
            JOptionPane.showMessageDialog(null,"Deleted");
           
            }catch(Exception e){
            JOptionPane.showMessageDialog(null,e);
            }
            }
        }                                        
    
        private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
    
        }                                     
    
        private void myTable1MouseClicked(java.awt.event.MouseEvent evt) {                                      
            try{
            int row=myTable1.getSelectedRow();
            String Table_click=(myTable1.getModel().getValueAt(row, 0).toString());
            String sql="select * from piante where codice_p='"+Table_click+"'";
            pst=conn.prepareStatement(sql);
            ResultSet rs=pst.executeQuery();
             if( rs.next()) {
             String add1=rs.getString("nome_botanico");
             jTextField1.setText(add1);
             String add2=rs.getString("nome_comune");
             jTextField2.setText(add2);
             String add3=rs.getString("esotica");
             jTextField3.setText(add3);
             String add4=rs.getString("giardino");
             jTextField4.setText(add4);
             String add5=rs.getString("prezzo");
             jTextField5.setText(add5);
             String add6=rs.getString("codice_p");
             jTextField6.setText(add6);
             }
            }catch(Exception e){
             JOptionPane.showMessageDialog(null,e);
            
            }
        }                                     
    
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            jTextField1.setText("");
            jTextField2.setText("");
            jTextField3.setText("");
            jTextField4.setText("");
            jTextField5.setText("");
            jTextField6.setText("");
        }                                        
    
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            try{
            String value1=jTextField6.getText();
            String value2=jTextField1.getText();       
            String value3=jTextField2.getText();
            String value4=jTextField3.getText();
            String value5=jTextField4.getText();
            String value6=jTextField5.getText();
            
            String sql="Update piante set codice_p='"+value1+ "',nome_botanico='"+value2+"',nome_comune='"+value3+"',giardino='"+value4+"',esotica='"+value5+"',prezzo='"+value6+"'where codice_p='"+value1+"'";
            pst=conn.prepareStatement(sql);
            pst.execute();
            JOptionPane.showMessageDialog(null,"Updated");
           
            }catch(Exception e){
                 JOptionPane.showMessageDialog(null,e);
            }
            
        }                                        
    
    
        /**
         * @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(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame1.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 NewJFrame1().setVisible(true);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton cmd_save;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JLabel jLabel5;
        private javax.swing.JLabel jLabel6;
        private javax.swing.JLabel jLabel7;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        private javax.swing.JTextField jTextField3;
        private javax.swing.JTextField jTextField4;
        private javax.swing.JTextField jTextField5;
        private javax.swing.JTextField jTextField6;
        private javax.swing.JTable myTable1;
        // End of variables declaration                   
    }
    
    
    Ecco il codice...
  • Re: Refresh Jtable

    luigi83 ha scritto:


    Ecco il codice...
    Vabbè ... il solito codice orripilante, prolisso e incomprensibile generato da un GUI editor ......
    Comunque si vede bene che hai usato DefaultTableModel. Nel costruttore crei e riempi un nuovo DefaultTableModel e poi lo assegni alla tabella.

    Sarebbe meglio innanzitutto se tieni il riferimento al tuo DefaultTableModel come variabile di istanza, così puoi usarlo anche altrove nella classe. Comunque DefaultTableModel è assolutamente "mutabile", quindi ad un certo punto, in un secondo momento, nessuno ti vieta di rifare la query che vuoi, rimuovere tutte le righe nel DefaultTableModel e aggiungerne altre nuove.
    Quindi quale è il dubbio o problema specifico?
Devi accedere o registrarti per scrivere nel forum
5 risposte