IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

NetBeans Java Discussion :

Ajout de ligne à JTable en appuyant sur TAB ou ENTER


Sujet :

NetBeans Java

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Septembre 2005
    Messages
    18
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2005
    Messages : 18
    Points : 13
    Points
    13
    Par défaut Ajout de ligne à JTable en appuyant sur TAB ou ENTER
    Bonjour mon Problème C'est que j'ai une Jtable au Départ elle ne possède aucune ligne j'ai un Bouton Ajouter (Btnajout voir la méthode en bas )qui peut créer une ligne la première fois mais pour les lignes qui sont suit il faut que je test si il est a la dernière colonne (3) puis il vérifie si la première colonne n'est pas vide et même je test si nombre de ligne est égale a la ligne sélectionné (pour moi si il est sur la dernière ligne il crée un nouvelle ligne sinon rien)
    j'ai essayé beaucoup de chose même avec Evénement KeyPressed J'arrive pas et j'ai lu la doc Oracle mais dommage qu'elle est en Anglais parce que j'ai la difficulté avec l'anglais J'ai vraiment besoin d'aide et merci
    voila mon code au complet :

    Code java : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    public class form1 extends javax.swing.JFrame {
    
        /**
         * Creates new form form1
         */
       Connection conn=null;
       ResultSet rs = null; 
       PreparedStatement pst = null; 
       JComboBox cb = new JComboBox();
     DefaultTableModel model;
        public form1() {
            initComponents();
     
      TableColumn tc = tblstudent.getColumnModel().getColumn(1);//C est la colonne ou je vais mettre mon combobox
      TableCellEditor tce = new DefaultCellEditor(cb);
      tc.setCellEditor(tce);
    tblstudent.getColumnModel().getColumn(3).setCellRenderer(new DateCellRenderer());
    tblstudent.getColumn("Date").setCellEditor(new CellDateEditor());//C'est la Colonne ou je vais mettre mon JDateChosser
            
    //DEBUT  Creation de l'evenement 
      
    tblstudent.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    tblstudent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1),"tab");
    tblstudent.getActionMap().put("tab",new AbstractAction(){
    @Override
    public void actionPerformed(ActionEvent e){
       
    if(tblstudent.getSelectedRow()==tblstudent.getRowCount()) {
                                if((tblstudent.getSelectedColumn()==3)&&(tblstudent.getValueAt(0, 0)!=null))
                
                                                                                                             model.addRow(new Object[]{null, null, null, null});}
     }
    });;
     //FIN  Creation de l'evenement listener  
     }
    
        /**
         * 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();
            tblstudent = new javax.swing.JTable();
            Btnajout = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowOpened(java.awt.event.WindowEvent evt) {
                    formWindowOpened(evt);
                }
            });
    
            tblstudent.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
            tblstudent.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
    
                },
                new String [] {
                    "Num", "Nom", "Prenom", "Date"
                }
            ));
            tblstudent.addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyPressed(java.awt.event.KeyEvent evt) {
                    tblstudentKeyPressed(evt);
                }
                public void keyTyped(java.awt.event.KeyEvent evt) {
                    tblstudentKeyTyped(evt);
                }
            });
            jScrollPane1.setViewportView(tblstudent);
    
            Btnajout.setText("Ajouter");
            Btnajout.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    BtnajoutActionPerformed(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()
                    .addGap(87, 87, 87)
                    .addComponent(Btnajout)
                    .addContainerGap(579, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 569, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(70, 70, 70))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(26, 26, 26)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(167, 167, 167)
                    .addComponent(Btnajout)
                    .addContainerGap(68, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>                        
    
        private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
            // TODO add your handling code here:
            conn=MaConnection.connectDB();
             RemplireCombo();
        }                                 
    
       @SuppressWarnings("empty-statement")
        private void BtnajoutActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
             DefaultTableModel model=(DefaultTableModel) tblstudent.getModel();
            int x = tblstudent.getRowCount();
         if (x==0) model.addRow(new Object[]{null, null, null, null});
            
         if (tblstudent.getValueAt(0, 0)==null ) { tblstudent.editCellAt(0,0);
            tblstudent.setRowSelectionInterval(0, 0); 
           tblstudent.getEditorComponent().requestFocusInWindow();           
            }else {tblstudent.editCellAt(x+1,0);
                tblstudent.setRowSelectionInterval(x+1, 0);
                tblstudent.getEditorComponent().requestFocusInWindow();           
            }
        }                                        
    
       @SuppressWarnings("empty-statement")
        private void tblstudentKeyPressed(java.awt.event.KeyEvent evt) {                                      
    //DefaultTableModel model=(DefaultTableModel) tblstudent.getModel();
         //(tblstudent.getSelectedRow()+1==tblstudent.getRowCount())&&
    /*  int x=tblstudent.getRowCount(); int y=tblstudent.getSelectedRow();
        /* if (evt.getKeyCode()==KeyEvent.VK_TAB ||evt.getKeyCode()==KeyEvent.VK_DOWN)&&(tblstudent.getSelectedRow()+1==tblstudent.getRowCount())&&(tblstudent.getSelectedColumn()==3)&&(tblstudent.getValueAt(0, 0)!=null)
                 {model.addRow(new Object[]{null, null, null, null});}
                 switch (evt.getKeyCode())
                 {case KeyEvent.VK_TAB:
                     {if ((tblstudent.getSelectedRow()+1==tblstudent.getRowCount())&&(tblstudent.getSelectedColumn()==3)&&(tblstudent.getValueAt(0, 0)!=null))
                    {model.addRow(new Object[]{null, null, null, null});}    
                 }break;
                 case KeyEvent.VK_DOWN:
                
                 }*/
     
        }                                     
    
        private void tblstudentKeyTyped(java.awt.event.KeyEvent 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/tu...feel/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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(form1.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 form1().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.JButton Btnajout;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable tblstudent;
        // End of variables declaration                   
    
    
    //Ma Procedure qui rempli mon Combobox
        private void RemplireCombo() {
        try {
      String sql= "select nomst from student";
     pst=conn.prepareStatement(sql);
     rs=pst.executeQuery();
     while (rs.next()){
     String nomst=rs.getString("nomst");
     cb.addItem(nomst);
     }
     }catch(Exception e){
          JOptionPane.showMessageDialog(null, e);
     }
        
        }
    }
    Images attachées Images attachées  

  2. #2
    Membre à l'essai
    Profil pro
    Inscrit en
    Septembre 2005
    Messages
    18
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2005
    Messages : 18
    Points : 13
    Points
    13
    Par défaut
    Bonjour S.V.P j'ai besoin d'aide
    je veux savoir pourquoi personne ne veut me répondre
    est ce que j'ai fais quelque chose qui n'est pas correcte au règlement du site et je ne sais pas ?
    j'attend la réponse s.v.p

  3. #3
    Traductrice
    Avatar de Mishulyna
    Femme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    1 504
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 1 504
    Points : 7 840
    Points
    7 840
    Par défaut
    Bonjour,

    Citation Envoyé par jean_Carlo Voir le message
    je veux savoir pourquoi personne ne veut me répondre
    Avez-vous pensé que la réponse à votre question n'est pas forcement connue par tous les utilisateurs de NetBeans (j'en connais une tellement nulle en Swing qu'elle fait encore des cauchemars au sujet de JTable)?!

    Citation Envoyé par jean_Carlo Voir le message
    est ce que j'ai fais quelque chose qui n'est pas correcte au règlement du site et je ne sais pas ?
    Je ne pense pas, sinon on vous l'aurait signalé (quoique, peut-être on vous a déjà parlé par le passé de l'existence d'autres sous-forums dédiés aux débutants?).

    Citation Envoyé par jean_Carlo Voir le message
    j'attend la réponse s.v.p
    En attendant, faites un petit tour par ici, vous y trouverez peut-être une réponse (un indice, une idée) utile pour sortir de l'impasse. Bonne chance!
    Chaque fois que tu dis "je ne peux pas", n'oublie pas d'ajouter le mot "encore".

  4. #4
    Membre à l'essai
    Profil pro
    Inscrit en
    Septembre 2005
    Messages
    18
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2005
    Messages : 18
    Points : 13
    Points
    13
    Par défaut
    Bonjour Mishulyna
    Merci Pour la Réponse et j'ai meme pas pensé pensé que la réponse à ma question n'est pas forcement connue par tous les utilisateurs de NetBeans
    et merci je vais voir le lien que tu m'as donné .
    S.V.P peux tu me dire C'est ou pour acceder au sous-forums dédiés aux débutants et merci d'avance.

  5. #5
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    Ta question est incompréhensible. Elle fait 3 lignes sur mon écran large sans la moindre ponctuation. C'est illisible et impossible à suivre. Donc commence par expliquer clairement ton problème.

    Concernant ton code, je vais déjà commenter ce petit bout de code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    if(tblstudent.getSelectedRow()==tblstudent.getRowCount())
    Cette condition ne pourra jamais être vraie, puisque le row sélectionné se situe dans la fourchette [0,rowCount-1]


    Concernant l'anglais, faudra t'y mettre si tu veux faire de la programmation.

  6. #6
    Traductrice
    Avatar de Mishulyna
    Femme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    1 504
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 1 504
    Points : 7 840
    Points
    7 840
    Par défaut
    Bonjour jean_Carlo,

    Explore un peu le forum Java.
    Tu y trouveras un sous-forum Général Java -> Débuter et un autre, Interphaces Graphiques en Java -> Débuter. Puisque apparemment tu étudies maintenant le développement des applications Swing, le sous-forum AWT/SWING pourrait aussi t'intéresser.
    Chaque fois que tu dis "je ne peux pas", n'oublie pas d'ajouter le mot "encore".

  7. #7
    Membre à l'essai
    Profil pro
    Inscrit en
    Septembre 2005
    Messages
    18
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2005
    Messages : 18
    Points : 13
    Points
    13
    Par défaut
    Bonjour tchize_ et Merci
    Bon voila entre puisque j'avais pas de réponce j'ai essayé ce Code que je vais copier en bas mias mon probleme C'est que j'essaye avec la touche ENTER de me déplacer entre le colonnes et aussitot que j'arrive a la 3eme colonne en tapant sur ENTER il me crée la ligne suivante mais il faut que les ligne de la ligne precedente ne soit pas vide mais avec ce code ca marche un peu sauf qu'il me crée des lignes meme si j'ai rien saisie dans les cellules
    vloila mon code avec un peu d'explication pour les Conditions if:
    package javaapplication5;

    import java.awt.event.*;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableColumn;



    /**
    *
    * @author Dell
    */
    public class form1 extends javax.swing.JFrame {

    /**
    * Creates new form form1
    */
    Connection conn=null;
    ResultSet rs = null;
    PreparedStatement pst = null;
    JComboBox cb = new JComboBox();
    DefaultTableModel model;
    public form1() {
    initComponents();

    TableColumn tc = tblstudent.getColumnModel().getColumn(1);//C est la colonne ou je vais mettre mon combobox
    TableCellEditor tce = new DefaultCellEditor(cb);
    tc.setCellEditor(tce);
    tblstudent.getColumnModel().getColumn(3).setCellRenderer(new DateCellRenderer());
    tblstudent.getColumn("Date").setCellEditor(new CellDateEditor());//C'est la Colonne ou je vais mettre mon JDateChosser
    //DEBUT Creation de l'evenement listenr

    //Va à la cellule suivante jusqu'au bout de la ligne puis à la ligne suivante etc...
    final Action CelluleSuivante = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {

    DefaultTableModel model=(DefaultTableModel) tblstudent.getModel();
    //ici je teste si je suis a la derniere ligne et que ma preminere colonne
    if ((tblstudent.getSelectedRow() == tblstudent.getRowCount()-1)&&(tblstudent.getValueAt(tblstudent.getSelectedRow(),0)!=null)){

    //Arrivé a la derniere colonne il va créer la ligne suivante
    if((tblstudent.getSelectedColumn() == 3)&&(tblstudent.getValueAt(tblstudent.getSelectedRow(), 0)!=null)){
    model.addRow(new Object[]{null, null, null, null});
    tblstudent.changeSelection(tblstudent.getSelectedRow()+1,0,false,false);
    tblstudent.editCellAt(tblstudent.getSelectedRow()+1,0);

    }
    else//il va vers la colonne suivante
    {
    tblstudent.changeSelection(tblstudent.getSelectedRow(),tblstudent.getSelectedColumn()+1,false,false);
    tblstudent.editCellAt(tblstudent.getSelectedRow(),tblstudent.getSelectedColumn());
    // tblstudent.setRowSelectionInterval(tblstudent.getSelectedRow(),tblstudent.getSelectedColumn());
    }
    }else // il n'est pas à la derniere ligne il se déplace vers la colonne suivante puis il met le curseur pour saisir
    {
    tblstudent.changeSelection(tblstudent.getSelectedRow(),tblstudent.getSelectedColumn()+1,false,false);
    tblstudent.editCellAt(tblstudent.getSelectedRow(),tblstudent.getSelectedColumn());}
    }
    };

    // Enleve le comportement de la touche Entrée
    javax.swing.InputMap inputMap = (javax.swing.InputMap)javax.swing.UIManager.get("Table.ancestorInputMap");
    // inputMap.remove(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER, 0));
    //tblstudent = new JTable(contenu,colonnes);
    tblstudent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),"ENTREE");
    tblstudent.getActionMap().put("ENTREE", CelluleSuivante);
    //L'ecouteur pour editer la cellule
    tblstudent.addKeyListener(new KeyAdapter(){
    public void keyPressed(KeyEvent e){
    if (e.getKeyCode() == KeyEvent.VK_ENTER){
    tblstudent.editCellAt(tblstudent.getSelectedRow(),tblstudent.getSelectedColumn());
    }
    }
    });

    //FIN Creation de l'evenement listener
    /* //DEBUT Creation de l'evenement listener
    tblstudent.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    tblstudent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1),"tab");
    tblstudent.getActionMap().put("tab",new AbstractAction(){
    @Override
    public void actionPerformed(ActionEvent e){

    if(tblstudent.getSelectedRow()==tblstudent.getRowCount()) {
    if((tblstudent.getSelectedColumn()==3)&&(tblstudent.getValueAt(0, 0)!=null))

    model.addRow(new Object[]{null, null, null, null});}
    }
    });int x=tblstudent.getRowCount(); int y=tblstudent.getSelectedRow();
    //FIN Creation de l'evenement listener */
    }

    /**
    * 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();
    tblstudent = new javax.swing.JTable();
    Btnajout = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowOpened(java.awt.event.WindowEvent evt) {
    formWindowOpened(evt);
    }
    });

    tblstudent.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    tblstudent.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] {

    },
    new String [] {
    "Num", "Nom", "Prenom", "Date"
    }
    ));
    tblstudent.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyPressed(java.awt.event.KeyEvent evt) {
    tblstudentKeyPressed(evt);
    }
    public void keyTyped(java.awt.event.KeyEvent evt) {
    tblstudentKeyTyped(evt);
    }
    });
    jScrollPane1.setViewportView(tblstudent);

    Btnajout.setText("Ajouter");
    Btnajout.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    BtnajoutActionPerformed(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()
    .addGap(87, 87, 87)
    .addComponent(Btnajout)
    .addContainerGap(579, Short.MAX_VALUE))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 569, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(70, 70, 70))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(26, 26, 26)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(167, 167, 167)
    .addComponent(Btnajout)
    .addContainerGap(68, Short.MAX_VALUE))
    );

    pack();
    }// </editor-fold>

    private void formWindowOpened(java.awt.event.WindowEvent evt) {
    // TODO add your handling code here:
    conn=MaConnection.connectDB();
    RemplireCombo();
    }

    @SuppressWarnings("empty-statement")
    private void BtnajoutActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    DefaultTableModel model=(DefaultTableModel) tblstudent.getModel();
    int x = tblstudent.getRowCount();
    if (x==0) model.addRow(new Object[]{null, null, null, null});
    tblstudent.editCellAt(0,0);
    if (tblstudent.getValueAt(0, 0)==null ) { tblstudent.editCellAt(0,0);
    tblstudent.setRowSelectionInterval(0, 0);
    tblstudent.getEditorComponent().requestFocusInWindow();
    }else {tblstudent.editCellAt(x+1,0);
    tblstudent.setRowSelectionInterval(x+1, 0);
    tblstudent.getEditorComponent().requestFocusInWindow();
    }
    }

    @SuppressWarnings("empty-statement")
    private void tblstudentKeyPressed(java.awt.event.KeyEvent evt) {
    //DefaultTableModel model=(DefaultTableModel) tblstudent.getModel();
    //(tblstudent.getSelectedRow()+1==tblstudent.getRowCount())&&
    /* int x=tblstudent.getRowCount(); int y=tblstudent.getSelectedRow();
    /* if (evt.getKeyCode()==KeyEvent.VK_TAB ||evt.getKeyCode()==KeyEvent.VK_DOWN)&&(tblstudent.getSelectedRow()+1==tblstudent.getRowCount())&&(tblstudent.getSelectedColumn()==3)&&(tblstudent.getValueAt(0, 0)!=null)
    {model.addRow(new Object[]{null, null, null, null});}
    switch (evt.getKeyCode())
    {case KeyEvent.VK_TAB:
    {if ((tblstudent.getSelectedRow()+1==tblstudent.getRowCount())&&(tblstudent.getSelectedColumn()==3)&&(tblstudent.getValueAt(0, 0)!=null))
    {model.addRow(new Object[]{null, null, null, null});}
    }break;
    case KeyEvent.VK_DOWN:

    }*/

    }

    private void tblstudentKeyTyped(java.awt.event.KeyEvent 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/tu...feel/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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(form1.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 form1().setVisible(true);
    }
    });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton Btnajout;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblstudent;
    // End of variables declaration


    //Ma Procedure qui rempli mon Combobox
    private void RemplireCombo() {
    try {
    String sql= "select nomst from student";
    pst=conn.prepareStatement(sql);
    rs=pst.executeQuery();
    while (rs.next()){
    String nomst=rs.getString("nomst");
    cb.addItem(nomst);
    }
    }catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
    }

    }
    }

Discussions similaires

  1. Réponses: 4
    Dernier message: 11/03/2013, 11h53
  2. [AC-2007] Ajouter des lignes à une liste basée sur une requête
    Par Cinesra dans le forum VBA Access
    Réponses: 2
    Dernier message: 01/12/2010, 13h19
  3. Réponses: 2
    Dernier message: 28/11/2009, 16h27
  4. Ajouter une ligne à JTable
    Par ShredLord dans le forum Composants
    Réponses: 1
    Dernier message: 13/11/2007, 22h15
  5. Réponses: 18
    Dernier message: 23/06/2007, 01h17

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo