Partage
  • Partager sur Facebook
  • Partager sur Twitter

Mise à jour dans un tableau qui ne fonctionne pas.

Sujet résolu
    29 juillet 2015 à 21:49:21

    Bonjour,

    Je travaille sur Netbeans  et PHPadmin, je voudrais sélectionner une ligne de mon tableau avec ma souris et appuyer sur le bouton modifier pour le modifier de façon instantanée. J'ai fouiller sur internet et j'ai trouver cela:

    int ligneSelectionne = taJTable.getSelectedRow(); 
    
    String outil = taJTable.getValueAt(ligneSelectionne, indexColonne);
    stmt=maconnexion.ObtenirConnexion().createStatement();
    String wql = "UPDATE table SET nom_outil=?"; 
    stmt.setString(1, outil); 
    stmt.executeUpdate(wql);

    J'ai essayé de l'adapter à mon code mais sans succes, ça marque setString,getValueAt,getSelectedRow cannot  find symbol.

    Voici mon code ;

    package gestionoutilbricolage;
    import java.sql.*;
    
    import javax.swing.table.DefaultTableModel; 
    
    import javax.swing.JTable;
    
    
    /**
     *
     *
     */
    public class FenetreListeOutil extends javax.swing.JFrame {
        String outil;
       Statement stmta;    
       Statement stmt;
       Statement stmtListeOutil;
       Connexion maconnexion = new Connexion();
    
        /** Creates new form FenetreListeOutil */
        public FenetreListeOutil() {
        
            initComponents();
            
            DefaultTableModel model = new DefaultTableModel();
            
            model.addColumn("NOM DE L' OUTIL"); 
            model.addColumn("FABRICANT");
            model.addColumn("ANNEE DE FABRICATION");
            model.addColumn("PRIX");
            
            
            
            String  requeteListeOutil = "select *from outil"; 
            try{
            
                stmtListeOutil=maconnexion.ObtenirConnexion().createStatement();
                ResultSet resultat = stmtListeOutil.executeQuery(requeteListeOutil);
                while(resultat.next()){
                 model.addRow (new Object[] {resultat.getString("nom_outil"),resultat.getString("fabricant_outil"),resultat.getString("annee_fabrication"),resultat.getString("prix_outil")});
                }
            }
            
            catch(SQLException ex){
                System.out.println(ex);
                
            }
            
            
         
            
            TableOutil.setModel(model);
        }
    
        /** 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() {
    
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            TableOutil = new javax.swing.JTable();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setName("Form"); // NOI18N
    
            org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gestionoutilbricolage.GestionOutilbricolageApp.class).getContext().getResourceMap(FenetreListeOutil.class);
            jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
            jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
            jLabel1.setName("jLabel1"); // NOI18N
    
            jScrollPane1.setName("jScrollPane1"); // NOI18N
    
            TableOutil.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {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"
                }
            ));
            TableOutil.setName("TableOutil"); // NOI18N
            jScrollPane1.setViewportView(TableOutil);
    
            jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
            jButton1.setName("jButton1"); // NOI18N
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
            jButton2.setName("jButton2"); // NOI18N
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(77, 77, 77)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(15, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(52, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(27, 27, 27)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(86, 86, 86))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2))
                    .addGap(66, 66, 66))
            );
    
            pack();
        }// </editor-fold>                        
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    
        
         
     String sql = "DELETE  FROM `outil` WHERE nom_outil='outil B'";
          
       try{
           
            stmt=maconnexion.ObtenirConnexion().createStatement();
         
           
      
          
          
          stmt.executeUpdate(sql);
      }    
          
           
        catch(SQLException ex){
        System.err.println(ex);
        }    
    }                                        
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    int ligneSelectionne = outil.getSelectedRow(); //récupère le numéro de la ligne selectionnée
    
    String outil = JTable.getValueAt(ligneSelectionne, indexColonne); //penser à remplacer indexColonne par le numéro de la colonne dont tu veux récupérer l'information (première colonne = 0)
    
    stmt=maconnexion.ObtenirConnexion().createStatement();
    String wql = "UPDATE outil SET nom_outil=fabricant A"; //Penser à ajouter le nom de la table et les conditions de selection
    stmt.setString(1, outil); //Cette instruction remplace le premier "?" trouvé dans la requête par la valeur de outil
    stmt.executeUpdate(wql);
    }                                        
    //Retourne vrai si la cellule est éditable : celle-ci sera donc éditable
    
     
    
    
        /**
         * @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(FenetreListeOutil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(FenetreListeOutil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(FenetreListeOutil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(FenetreListeOutil.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() {
                    new FenetreListeOutil().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JTable TableOutil;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        // End of variables declaration                   
    
    
    
    
    }
    


    Que dois je faire pour que ça marche?



    -
    Edité par bobivlog 29 juillet 2015 à 21:50:52

    • Partager sur Facebook
    • Partager sur Twitter
      30 juillet 2015 à 16:32:04

      Bonjour, 

      je pense que ton String outil est mal fait. car tu fais JTable.getValueAt(), il faut qu'à la place de JTable tu mettes ta JTable à toi (la seule que je vois est TableOutil)

      • Partager sur Facebook
      • Partager sur Twitter
        5 août 2015 à 22:14:41

        akinatorus a écrit:

        Bonjour, 

        je pense que ton String outil est mal fait. car tu fais JTable.getValueAt(), il faut qu'à la place de JTable tu mettes ta JTable à toi (la seule que je vois est TableOutil)


        Merci,

        je voudrais appliquer la même méthode pour supprimer. Je voudrais sélectionner une ligne de mon tableau avec ma souris et appuyer sur le bouton supprimer  pour le supprimer de façon instantanée, dans mon tableau et ma base de donnée de façon dynamique sans être obligé d'indiquer la ligne dans mon côte à chaque fois (comme une application de professionnel).

        J'ai pensé à cela,

         int ligneSelectionne = TableOutil.getSelectedRow(); 
        String outil = TableOutil.getValueAt(ligneSelectionne, 0).toString(); 
          PreparedStatement stmt = null;
        String wql = "DELETE  FROM `outil` WHERE nom_outil='?'";
        try {
            maconnexion.setAutoCommit(false);
            stmt = maconnexion.prepareStatement(wql);
            stmt.setString(1, "outil A");
            stmt.setString(2, "outil avant");
            stmt.executeUpdate();
            maconnexion.commit();
            } catch (SQLException e ) {
              Connexion.printSQLException(e);
                if (maconnexion != null) {
                    try {
                        System.err.print("Transaction is being rolled back");
                        maconnexion.rollback();
                    } catch(SQLException excep) {
                      Connexion.printSQLException(excep);
                    }
                }

        Si je me trompe pourrais je avoir la réponse s'il vous plait de quoi je devrais mettre avec un exemple.

        • Partager sur Facebook
        • Partager sur Twitter

        Mise à jour dans un tableau qui ne fonctionne pas.

        × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
        × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
        • Editeur
        • Markdown