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

avec Java Discussion :

Gestion d'un treeset


Sujet :

avec Java

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 53
    Points : 29
    Points
    29
    Par défaut Gestion d'un treeset
    Bonjour, j'utilise dans une classe un treeset statique des objets de cette classe or le programme ne fonctionne pas avec cet arbre, étant débutante je n'ai pas tout compris aux gestions de ces structures de données et je ne vois pas d'ou viens mo erreur, pouvez vous m'aider?

    Voici ma classe la ligne en rouge stoppe le programme quand elel doit s'executer

    Code : 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
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package PFiches;
    
    import java.util.*;
    
    /**
     *
     * @author Aurélie 
     */
    public class Cmotcle {
        //déclaration des attributs
       private String mot_cle;
       //liste des photos associées à un mot-clé
       private LinkedList<Cphoto> photos = new LinkedList<Cphoto>();
       //arbre contenant tous les mots-clés
       private static TreeSet motcle = new TreeSet();
       
       //déclaration du constructeur lorsqu'un nouveau mot-clé est associé à une photo
       public Cmotcle (String mot, Cphoto photo_taggée){
           mot_cle=mot;
           photos.add(photo_taggée);
           motcle.add(this);
       }
    
       //déclaration du constructeur lors du lancement du programme
       public Cmotcle(String mot){
           mot_cle=mot;
           motcle.add(this);
       }
       
       //////////////////////Déclaration des méthodes
       
       //Méthode d'ajout d'une photo dans la liste du mot-clé
       public void Ajout_photo(Cphoto photo){
           photos.add(photo);
       }
       
       //Méthode de retrait d'une photo de la liste d'un mot-clé 
       public void Retirer_photo(Cphoto photo){
           photos.remove(photo);
       }
       
       //Recherche d'une photo par son titre
       public Cphoto Rechercher_photo(String tit){
           //déclaration d'un itérateur pour parcourir la liste de photos
           Iterator iter;
           iter = photos.iterator();
           while (iter.hasNext() ){
               Cphoto photo =(Cphoto) iter.next();
                if ((photo.get_titre()).equals(tit)){
                        return(photo);
               }
           }
             return(null);  
           }
       
       static public boolean existence_mc(String MC){
           Iterator iter;
           iter = motcle.iterator();
           while(iter.hasNext()){
               Cmotcle mocle = (Cmotcle) iter.next();
               if(mocle.mot_cle.equals(MC)){
                   return(true);
               }
           }
           return(false);
       }
       static public Cmotcle rechercher_mc(String MC){
           Iterator iter;
           iter = motcle.iterator();
           while(iter.hasNext()){
               Cmotcle mocle = (Cmotcle) iter.next();
               if(mocle.mot_cle.equals(MC)){
                   return(mocle);
               }
           }
           return(null);
       }
       
       public void ajout_mc_arbre (){
           motcle.add(this);
       }
           
       }
    et voici la classe ou je fais appel à cet arbre (classe graphique) via la ligne en rouge qui a pour but de créer l'arbre

    Code : 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
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    /*
     * CFAccueil.java
     *
     * Created on 11 février 2009, 11:00
     */
    
    package PFiches;
    
    
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JOptionPane;
    
    /**
     *
     * @author  Fanny
     */
    public class CFAccueil extends javax.swing.JFrame {
        
        CFMenu FMenu;
        CFCreerProfil FCréerProfil;
        CFRechercheMC FRechercheMC;
        String nom;
        String m_d_p;
    
    
    
    
        /** Creates new form CFAccueil */
        public CFAccueil() throws FileNotFoundException, IOException {
            initComponents();
            FCréerProfil = new CFCreerProfil(this,false);
            FRechercheMC = new CFRechercheMC(this,false);
            FMenu = new CFMenu(this,false);
            //Lecture des fichier       
            Cutilisateur.lecture_ut();
            Cphoto.lecture_photo();
    
        }
    
        /** 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() {
    
            lTexteaccueil = new javax.swing.JLabel();
            tfNom = new javax.swing.JTextField();
            lTexteaccueil1 = new javax.swing.JLabel();
            pfMotdePasse = new javax.swing.JPasswordField();
            lMotdePasse = new javax.swing.JLabel();
            bOK = new javax.swing.JButton();
            bQuitter = new javax.swing.JButton();
            bCréationProfil = new javax.swing.JButton();
            jSeparator1 = new javax.swing.JSeparator();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Accueil");
            setBackground(java.awt.Color.darkGray);
            setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            setForeground(new java.awt.Color(0, 204, 0));
    
            lTexteaccueil.setFont(new java.awt.Font("Tahoma", 0, 24));
            lTexteaccueil.setText("Bienvenue sur Mezimages");
    
            tfNom.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    tfNomActionPerformed(evt);
                }
            });
    
            lTexteaccueil1.setText("Entrez votre identifiant :");
    
            pfMotdePasse.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    pfMotdePasseActionPerformed(evt);
                }
            });
    
            lMotdePasse.setText("Entrez votre mot de passe :");
    
            bOK.setText("OK");
            bOK.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    bOKActionPerformed(evt);
                }
            });
    
            bQuitter.setText("Quitter");
            bQuitter.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    bQuitterActionPerformed(evt);
                }
            });
    
            bCréationProfil.setText("Créer un profil");
            bCréationProfil.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    bCréationProfilActionPerformed(evt);
                }
            });
    
            jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
    
            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(56, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(lTexteaccueil)
                            .addGap(61, 61, 61))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addComponent(bOK)
                                    .addGap(49, 49, 49))
                                .addComponent(lTexteaccueil1)
                                .addComponent(tfNom, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
                                .addComponent(lMotdePasse)
                                .addComponent(pfMotdePasse, javax.swing.GroupLayout.Alignment.TRAILING))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(117, 117, 117)
                                    .addComponent(bQuitter)
                                    .addContainerGap())
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addGap(18, 18, 18)
                                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(bCréationProfil)
                                    .addGap(48, 48, 48))))))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(36, 36, 36)
                    .addComponent(lTexteaccueil, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(18, 18, 18)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(34, 34, 34)
                                    .addComponent(lTexteaccueil1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(tfNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(32, 32, 32)
                                    .addComponent(lMotdePasse)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(pfMotdePasse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(bOK))
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(81, 81, 81)
                                    .addComponent(bCréationProfil)))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                            .addComponent(bQuitter)))
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>                        
    
    private void bOKActionPerformed(java.awt.event.ActionEvent evt) {                                    
        boolean connexion;
        String mdp = new String (pfMotdePasse.getPassword());
        m_d_p=mdp;
        connexion=Cutilisateur.verif_connexion(tfNom.getText(),mdp );  
        nom = tfNom.getText();
        if(connexion){
            Cutilisateur utilisateur = new Cutilisateur(tfNom.getText(),mdp);
                this.setVisible(false);
                FMenu.recup_util(utilisateur);
                FMenu.setVisible(true);
                
        } else {
            JOptionPane.showMessageDialog(this, "Identifiant ou mot de passe incorrect");
        }
    
        
    }                                   
    
    private void tfNomActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    }                                     
    
    private void bQuitterActionPerformed(java.awt.event.ActionEvent evt) {                                         
            try {
                Cutilisateur.enregistrement_fich();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(CFAccueil.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(CFAccueil.class.getName()).log(Level.SEVERE, null, ex);
            }
        System.exit(0);
    }                                        
    
    private void bCréationProfilActionPerformed(java.awt.event.ActionEvent evt) {                                                
    this.setVisible(false);
     FCréerProfil.setVisible(true);
    }                                               
    
    private void pfMotdePasseActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:
    }                                            
    
    public String get_nom(){
        String nom; 
        return(tfNom.getText());
    }
    
    public String get_mdp(){
        String mdp = new String (pfMotdePasse.getPassword());
        return(mdp);
    }
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        new CFAccueil().setVisible(true);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(CFAccueil.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(CFAccueil.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.JButton bCréationProfil;
        private javax.swing.JButton bOK;
        private javax.swing.JButton bQuitter;
        private javax.swing.JSeparator jSeparator1;
        private javax.swing.JLabel lMotdePasse;
        private javax.swing.JLabel lTexteaccueil;
        private javax.swing.JLabel lTexteaccueil1;
        private javax.swing.JPasswordField pfMotdePasse;
        private javax.swing.JTextField tfNom;
        // End of variables declaration                   
    
    
    
    }

  2. #2
    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
    1) quelle est l'erreur? Que se passe-t-il versus que devrait-il se passer?
    2) stocker statiquement dans un classe toutes ces instance, bien que c'est faisable, c'est pas ce qu'il y a des plus propre. Si t'as une liste de mots clés, la logique voudrait de définir une classe dictionnaire qui les gère, par exemple.

  3. #3
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 53
    Points : 29
    Points
    29
    Par défaut
    Quand je lance mon programme, je lis un fichier texte qui contient les mot-clés qui sont alors instanciés et ajoutés à l'arbre. Seulement dans le constructeur lorsque le programme execute la ligne d'ajout à l'arbre le programme se bloque systematiquement comme si l'arbre n'existait pas.

  4. #4
    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
    on peux voir le code appelé et l'erreur générée?

  5. #5
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 53
    Points : 29
    Points
    29
    Par défaut
    voici la classe Cphoto avec la procédure lecture_photo qui bug

    Code : 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
    package PFiches;
     
    import java.io.*;
    import java.util.Iterator;
    import java.util.LinkedList;
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    /**
     *
     * @author Aurélie
     */
    public class Cphoto {
     
        //déclaration des attributs
        private String identifiant;
        private String titre;
        private String commentaire;
        //liste dynamique de mots-clés
        private LinkedList<String> mot_cle = new LinkedList<String>();
        private String adresse;
        private boolean trouve;
     
        //déclaration des attributs de classe : liste dynamique de photos
        static private LinkedList<Cphoto> liste_photo=new LinkedList<Cphoto>();
     
        //constructeur du début du programme
        public Cphoto( String cop[] ){
            //affectation des attributs à partir du tableau de données du fichier texte 
            identifiant=cop[0];
            titre=cop[1];
            commentaire=cop[2];
            for (int i=3;i<cop.length;i++){
                mot_cle.add(cop[i]);
                //ajout du mot clé à l'abre
                //si le mot clé est déjà repertorié
                if(Cmotcle.existence_mc(cop[i])){
                    Cmotcle mot_cle =  Cmotcle.rechercher_mc(cop[i]);
                    mot_cle.Ajout_photo(this);
                } else {
                    //si le mot-clé n'est pas repertorié creation du mot clé
                    Cmotcle mot_cle = new Cmotcle (cop[i], this);
                    //ajout du mot_clé à l'arbre
                    mot_cle.ajout_mc_arbre();
                }
            }
            trouve=false;
            //ajout de la photo à la liste des photos
            liste_photo.add(this);
        }
     
        //constructeur lors de l'ajout d'une photo
        public Cphoto(String id, String tit, String comm, LinkedList<String> mc){
            // affectation des attributs des photos lors de l'ajout d'une photo
            identifiant = id;
            titre = tit;
            commentaire = comm;
            trouve=false;
            //ajout de la photo à la liste des photos
            liste_photo.add(this);
            mot_cle=mc;}
     
        //constructeur d'une photo après avoir cherché la photo sur le navoguateur
        public Cphoto(String ad){
            adresse=ad;
        }
     
        //Ajout d'une photo dans la liste des photod
        public void ajout_photo(){
            liste_photo.add(this);
      }
     
        //retrait d'une photo de la liste des photos
        public void retrait_ut(){
            liste_photo.remove(this);
        }
     
     
        //affichage des caractéristiques des photos
            public void afficher_infos(){
            System.out.println("identifiant : " + identifiant);
            System.out.println("titre : " + titre);
            System.out.println("commentaire : " + commentaire);
            System.out.println("Mots-clés : "+ mot_cle);
     
        }
     
     
        //affichage des objets photos
        static public void afficher_liste_photos(){
            // déclaration et initialisation d'un itérateur parcourant la liste de photos
            Iterator  iter =liste_photo.iterator();
            //tant que l'on n'a pas parcouru toute la liste
            while (iter.hasNext() ){
               Cphoto photo =(Cphoto) iter.next();
               //affichage des informations de chaque photo
               photo.afficher_infos();
               }
           }
     
        //obtenir le titre d'une photo
        public String get_titre(){
            return(this.titre);
        }
     
        //lecture du fichier contenant les informations des photos
        static void lecture_photo() throws FileNotFoundException, IOException{
        //précision du fichier texte concerné
        String nom_fich="photo.txt";
        FileReader fichier = new FileReader (nom_fich); 
        BufferedReader in  = new BufferedReader(fichier);
        String ligne;
        //on commence la lecture à la premiere ligne du fichier
        ligne = in.readLine();
        //tant que l'on n'a pas parcouru tout le fichier,
        while(ligne!= null){
           String infos[];
           //on découpe la ligne selon les underscores 
           //on remplit le tableau infos avec infos de la ligne
           infos = ligne.split("_");
           //instanciation de la classe de photos
           Cphoto photo = new Cphoto(infos);
           //on passe à la ligne suivante
           ligne=in.readLine();       
            }
     //test de la procédure  
     //Cphoto.afficher_liste_photos();
     //fermeture du fichier
     fichier.close();
    }
     
        //procédure d'écriture du fichier 
        static void enregistrement_fich()throws FileNotFoundException, IOException{
        //création d'un nouveau fichier texte
        File fichier = new File("photo.txt");
        FileWriter out = new FileWriter(fichier);
        //instanciation d'un itérateur pour parcourir la liste de photos
        Iterator iter = liste_photo.iterator();
        //tant que l'on n'a pas parcouru toute la liste
        while (iter.hasNext()){
            Cphoto photo =(Cphoto) iter.next();
            //écriture dans le fichier
            out.write(photo.identifiant+"_"+ photo.titre + "_" + photo.commentaire);
             //instanciation d'un itérateur pour parcourir la liste des mots-clés des photos
            Iterator iter2 = photo.mot_cle.iterator();
            //tant que l'on a pas parcouru la liste
            while (iter2.hasNext()){
                String motcle = (String)iter2.next();
                //écriture dans le fichier
                out.write("_"+motcle);
            }
            //passage à la ligne dans le fichier
            out.write("\r\n");
        }
        //fermeture du fichier
        out.close();
    }
     
        //procédure de changement de titre
        public void settitre(String tit){
            titre=tit;
        }
     
        public void setcom(String com){
            commentaire = com;
        }
     
        public void ajout_mc (String MC){
            mot_cle.add(MC);
        }
    }
    et voici le message d'erreur :

    init:
    deps-jar:
    compile:
    run:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: PFiches.Cmotcle cannot be cast to java.lang.Comparable
    at java.util.TreeMap.put(TreeMap.java:542)
    at java.util.TreeSet.add(TreeSet.java:238)
    at PFiches.Cmotcle.ajout_mc_arbre(Cmotcle.java:85)
    at PFiches.CFAjouterPhoto.jBOkActionPerformed(CFAjouterPhoto.java:173)
    at PFiches.CFAjouterPhoto.access$300(CFAjouterPhoto.java:17)
    at PFiches.CFAjouterPhoto$4.actionPerformed(CFAjouterPhoto.java:73)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6038)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
    at java.awt.Component.processEvent(Component.java:5803)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    at java.awt.Container.dispatchEventImpl(Container.java:2102)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    En fait pour faire clair : en faisant du pas à pas la procédure Cphoto.lecture_photo n'aboutit à rien le programme s'arrête sans explication, la fenêtre graphique se ferme.
    Sans faire de pas à pas le programme se lance, ( il s'agit d'une photothèque) la connexion de l'utilisateur marche mais l'ajout d'une photo ne fonctionne pas
    en effet je dois alors ajouter les mot clés associés à la photo dans l'arbre de smots clés
    d'apres ce message d'erreurs
    at PFiches.Cmotcle.ajout_mc_arbre(Cmotcle.java:85)
    c'est cette procédure qui ne fonctionne pas:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
       public void ajout_mc_arbre (){
           motcle.add(this);
       }
    je ne vois pas ou ets le pb... peut etre l'arbre est il mal déclaré mais je pense avoir tout fait ( cf la classe Cmotcle dans mon premier post)
    Merci beaucoup pour votre aide

  6. #6
    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
    a ben de fait, comme le dit le message d'erreur à demi mot, ta classe CmotClet doit implémenter l'interface Comparable, ce qu'elle ne fait pas -> erreur dans le TreeSet quand il essaie de déterminer l'ordre des éléments.

  7. #7
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 53
    Points : 29
    Points
    29
    Par défaut
    Et comment je peux implémenter cette interface?

  8. #8
    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
    en ajoutant "implements Comparable" dans la définition de la classe et en implémentant les méthodes de l'interface Comparable dans ta classe.

  9. #9
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 53
    Points : 29
    Points
    29
    Par défaut
    D'accord merci. Qu'entend tu par implémenter le sméthodes dans ma classe? En effet j'ai déjà utilisé des arbres dans d'autres programmes et je n'avais pas besoin de faire toute ces démarches.

  10. #10
    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
    TreeSet ne prend que des objet comparable, pour pouvoir justement les ordonner. Et permettre un un objet de se comparer à un autre, c'est le boulot de l'interface Comparable

    Citation Envoyé par sun
    public interface Comparable<T>

    This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

    Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or elements in a sorted set, without the need to specify a comparator.
    Note que t'es pas obligé de faire implémenter comparable à tes MotCles, tu peux aussi préférer de construire ton TreeSet en lui passant en paramètre un implémentation de Comparator<MotCle>


    Pour savoir comment implémenter une interface, voir les cours de base de java.

  11. #11
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 53
    Points : 29
    Points
    29
    Par défaut
    D'accord, merci pour ces informations. Mais je ne sais pas du tout comment récupérer la bonne méthode de comparator à implémenter et que dois-je implémenter?Une procédure de comparaison qui renvoie 1 ou 0 selon inferiorité etc?
    Je sais je n'ai pas les bases, je subis le java, ceci est mon dernier TP et je lache un peu prise... En tout cas merci beaucoup pour votre aide




  12. #12
    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
    Tout est documenté dans l'api java:
    http://javasearch.developpez.com/j2s...l#compareTo(T)

  13. #13
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 53
    Points : 29
    Points
    29
    Par défaut
    Merci beaucoup pour le lien, entre temps un prof m'a suggéré d'implémenter l'interface comparator de cette manière :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
        public int compare(Object o1, Object o2) {
     //méthode permettant de comparer deux mot-clés
     //renvoie 0 si mc1==mc2 et un entier positif si mc1>mc2       
            String mc1=((Cmotcle)o1).GetTitle();
            String mc2=((Cmotcle)o2).GetTitle();
            return mc1.compareTo(mc2);
        }


    Maintenant quand je fais tourner le programme il n'y aucune amélioration... la ligne
    Cmotcle mocle = (Cmotcle) iter.next();
    ne marche pas... et je ne vois pas pourquoi

  14. #14
    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
    tu as le choix entre faire implémenter à CMotCle l'interface Comparable (que je t'ai pointée) ou fournir au TreeSet, à sa construction, un Comparator (ce que ton prof te suggère).

    Pour ton code, j'y vois pas d'erreur. Pourrais-tu etre plus précis sur 'le transtypage ne marche pas', quelle erreur as-tu?

  15. #15
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 53
    Points : 29
    Points
    29
    Par défaut
    Dsl j'ai changé mon message.. J'ai changé mes méthodes pour que le transtypage marche.
    Cmotcle mocle = (Cmotcle) iter.next(); cette ligne pose toujours un problème comme si l'utilisation d'un iterator n'est pas adapté pour l'arbre mais alors comment le parcourir?
    en tout cas un grand merci pour l'aide

  16. #16
    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
    pourriez vous préciser "ne marche pas" s'il vous plaît.

  17. #17
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    53
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 53
    Points : 29
    Points
    29
    Par défaut
    Bon cela devient compliqué alors je récapitule :

    voici les erreurs affichées par netbeans :

    init:
    deps-jar:
    compile:
    run:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to PFiches.Cmotcle
    at PFiches.Cmotcle.existence_mc(Cmotcle.java:70)
    at PFiches.Cphoto.<init>(Cphoto.java:41)
    at PFiches.Cphoto.lecture_photo(Cphoto.java:126)
    at PFiches.CFAccueil.<init>(CFAccueil.java:39)
    at PFiches.CFAccueil$6.run(CFAccueil.java:233)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

    et voici la procédure qui pose problème

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
       static public boolean existence_mc(Cmotcle MC){
           Iterator iter;
           iter = motcle.iterator();
           while(iter.hasNext()){
               Cmotcle mocle = (Cmotcle) iter.next();
               if(mocle.mot_cle.equals(MC)){
                   return(true);
               }
           }
           return(false);
       }

    avec en rouge la ligne qui pose problème. Le programme s'arrête directement en executan cette lign et je ne sais pas pourquoi...

  18. #18
    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
    Citation Envoyé par aurelie689 Voir le message
    java.lang.String cannot be cast to PFiches.Cmotcle
    ....
    Le programme s'arrête directement en executan cette lign et je ne sais pas pourquoi...
    Pourtant, il suffit de lire l'erreur. Ton iterateur te retourne un String et toi t'essaie de le Caster en PFiches.Cmotcle. Ce qui veux dire que ton set "mot_cle" contient des String et non pas des Cmotcle, ce que confirme la ligne suivante de ton code

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
        public Cphoto( String cop[] ){
            .....
                mot_cle.add(cop[i]);
    Pour éviter ce genre d'erreur, il vaut mieux utiliser les générics, qui permettent au compilateur de s'assurer du typage.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 2
    Dernier message: 31/08/2002, 21h37
  2. Gestion de matrice
    Par bzd dans le forum C
    Réponses: 4
    Dernier message: 12/08/2002, 18h19
  3. Réponses: 4
    Dernier message: 04/07/2002, 12h31
  4. c: gestion des exceptions
    Par vince_lille dans le forum C
    Réponses: 7
    Dernier message: 05/06/2002, 14h11
  5. gestion d'un joystick ...
    Par Anonymous dans le forum DirectX
    Réponses: 1
    Dernier message: 23/05/2002, 12h53

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