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

Composants Java Discussion :

[JTree]problème de rafraichissement [FAQ]


Sujet :

Composants Java

  1. #1
    Membre actif
    Inscrit en
    Juillet 2003
    Messages
    407
    Détails du profil
    Informations forums :
    Inscription : Juillet 2003
    Messages : 407
    Points : 252
    Points
    252
    Par défaut [JTree]problème de rafraichissement
    bonjour ,
    j'utilise un jtree , je n'arrive pas à le rafraichir apres modification de la structure qui affiche (exp : suppresion d'un fichier)

    exp : si l'utilisateur clique sur un fichier , un traitement sera lancé , si le fichier est déféctueux oar exemple je le supprime , mais je dois auusi le supprimer de l'affichage dans le jtree


    j'ai cherché et j'ai trouvé ca mais ca n'a aucun effet :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    DefaultTreeModel model= (DefaultTreeModel)tree.getModel();
    model.reload(top);//top est 
    principalframe.repaint();// principalframe est la frame principale qui contient plusieurs objets dont fait partie le jtree fais partie
    ;-) cordialement

  2. #2
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2002
    Messages
    16
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2002
    Messages : 16
    Points : 20
    Points
    20
    Par défaut
    Bonjour,

    Pourrais-tu donner le code où tu supprimes le noeud ?

    As-tu essayé la méthode model.nodeChanged(node) ?

    Le code que tu as donné est-il executé dans le Listener attaché au model ?

  3. #3
    Membre actif
    Inscrit en
    Juillet 2003
    Messages
    407
    Détails du profil
    Informations forums :
    Inscription : Juillet 2003
    Messages : 407
    Points : 252
    Points
    252
    Par défaut
    oh !!

    peut etre je ne suis pas entrain de faire ce qu'il faut !!

    je suis entrain de supprimer seulement le fichier (file.delete()) et je ne touche pas aux noeuds
    et j'ai cru qu'en faisant reload() , ca génèrera un nouveau tree du noued que je lui passe !!!!!

    alors comment il faut faire !!
    ;-) cordialement

  4. #4
    Membre régulier
    Homme Profil pro
    Architecte technique
    Inscrit en
    Avril 2003
    Messages
    79
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Architecte technique

    Informations forums :
    Inscription : Avril 2003
    Messages : 79
    Points : 107
    Points
    107
    Par défaut
    Salut,

    Si tu n'as pas supprimé ton noeud en parrallèle d'avoir supprimé ton fichier, tu peux reloader ton root cela ne changera rien.

    A+

  5. #5
    Membre actif
    Inscrit en
    Juillet 2003
    Messages
    407
    Détails du profil
    Informations forums :
    Inscription : Juillet 2003
    Messages : 407
    Points : 252
    Points
    252
    Par défaut
    alors il faut supprimer en // le noeud !!!

    et pour ajouter un fichier dans le tree à un emplacement définie (par un chemin absolue) il faut aussi ajouter le noeud !!!! il faut retrouver le noeud père
    je crain qu eje me perds avec les chemin

    c compliqué alors !!
    ;-) cordialement

  6. #6
    Membre régulier
    Homme Profil pro
    Architecte technique
    Inscrit en
    Avril 2003
    Messages
    79
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Architecte technique

    Informations forums :
    Inscription : Avril 2003
    Messages : 79
    Points : 107
    Points
    107
    Par défaut
    Ben oui il faut également ajouter un node lors d'un ajout de fichier.
    Mais si tu as peur de ne pas te retrouver dans tes noeuds tu peux toujours reconstruire l'ensemble de ton modèle à chaque fois que tu ajoutes ou supprimes un fichier.

  7. #7
    Membre régulier
    Homme Profil pro
    Architecte technique
    Inscrit en
    Avril 2003
    Messages
    79
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Architecte technique

    Informations forums :
    Inscription : Avril 2003
    Messages : 79
    Points : 107
    Points
    107
    Par défaut
    Sinon pour retouver le noeud père comme tu dis, tu peux passer par un TrrePath qui représente le chemin de ton repertoire (ex : c:\rep1\rep2)
    et récupérer ton noeud à partir de là

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent();
    En espérant que cela t'aide.

    A+

  8. #8
    Membre actif
    Inscrit en
    Juillet 2003
    Messages
    407
    Détails du profil
    Informations forums :
    Inscription : Juillet 2003
    Messages : 407
    Points : 252
    Points
    252
    Par défaut
    Bonjour ,
    voila mon code
    si kkun peut le tester et m'aider à reconstruire le modèle ,
    exp :
    si je clique sur un fichier j'ai essayé de changer le tree vers e: (dans la partie /////update ///// dans la méthode tarit_affiche)
    mais je n'ai pas réussi à le faire !
    kkun peut m'aider svp
    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
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
     
    package decodeur;
     
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.UIManager;
     
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.*;
    import javax.swing.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
     
    import java.net.URL;
    import java.io.*;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.*;
    import java.awt.*;
    import oracle.xml.parser.v2.*;
    import org.w3c.dom.*;
    import java.awt.event.*;
     
     
    public class Explorer extends JPanel implements TreeSelectionListener {
        public static JEditorPane htmlPane;
        private JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        public static JTree tree;
        private JScrollPane treeView ;
        public static String racineName ;
        public DefaultMutableTreeNode category = null;
        public DefaultMutableTreeNode book = null;
        public DefaultMutableTreeNode top = null;
        private static boolean useSystemLookAndFeel =false;
        public static JFrame principalframe = new JFrame();
        public static Image img ;
        public static java.awt.Dimension screenSize  ;
        public static decodeur dc = new decodeur();
        public static Progress pr = new Progress();
        public static String nomPatient = null ;
        public static String prenomPatient = null ;
        public static String date = null;
        public Explorer(String path) {
            super(new GridLayout(1,0));
            this.racineName = path;
            //Create the nodes.
            top = new DefaultMutableTreeNode(path);
            createNodes(top);
            //Create a tree that allows one selection at a time.
            tree = new JTree(top,true);
            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
     
            //ImageIcon leafIcon = new ImageIcon("Logo-.jpeg");
            /*if (leafIcon != null)
              {
              DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
              renderer.setLeafIcon(leafIcon);
              tree.setCellRenderer(renderer);
              }*/
     
     
            //Listen for when the selection changes.
            tree.addTreeSelectionListener(this);
            tree.putClientProperty("JTree.lineStyle","Angled");
     
            //Create the scroll pane and add the tree to it.
            JScrollPane treeView = new JScrollPane(tree);
     
     
            //Create the HTML viewing pane.
            htmlPane = new JEditorPane();
            htmlPane.setEditable(false);
            htmlPane.setContentType("text/html");
            JScrollPane htmlView = new JScrollPane(htmlPane);
     
            //Add the scroll panes to a split pane.
     
            splitPane.setTopComponent(treeView);
            splitPane.setBottomComponent(htmlView);
     
     
            splitPane.setDividerLocation(200);
            splitPane.setSize(500, 300);
            add(splitPane);
     
            principalframe.getContentPane().add(this);
            /** Le menu de l'application**/
            JMenuBar MenuBar1 = new JMenuBar();
            principalframe.setJMenuBar(MenuBar1);
               /*menus*/
            JMenu filemenu = new JMenu("Fichier");
            JMenu aidemenu = new JMenu("Aide");
               /*sous menus*/
            JMenuItem decContentItem = new JMenuItem("Décoder");
            JMenuItem aboutContentItem = new JMenuItem("A propos");
            JMenuItem helpContentItem = new JMenuItem("Aide");
              /*actions*/
     
            decContentItem.addActionListener(
             new ActionListener()
             {
                 public void actionPerformed(ActionEvent ev)
                 {
                     execWindow window = new execWindow();
                     window.setVisible(true);
                     dc.start();
                     pr.start();
     
                 }
             });
     
           aboutContentItem.addActionListener(
           new ActionListener()
            {
                 public void actionPerformed(ActionEvent ev)
                 {
                      Apropos prop = new Apropos();
                      prop.setVisible(true);
                 }
             });
     
           ActionListener helpcontentListener = Help.ActionHelp();
           helpContentItem.addActionListener(helpcontentListener); 
           helpContentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1,0));
     
           filemenu.add(decContentItem);
           aidemenu.add(aboutContentItem);
           aidemenu.add(helpContentItem);
     
           MenuBar1.add(filemenu);
           MenuBar1.add(aidemenu);
     
           screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
           //this.setLocation((int)((screenSize.width-this.getWidth())/2) ,(int)( (screenSize.height-this.getHeight())/2));
          // img = Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("decode/images/Logo.jpeg"));
     
           }
     
        //}
     
        /** Required by TreeSelectionListener interface. */
        public void valueChanged(TreeSelectionEvent e) {
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
           htmlPane.setText("");
           decodeur.file = null;
           traite_affichage(node);
         }
     
        private void createNodes(DefaultMutableTreeNode top) {
     
            File racine = new File(racineName);
            remplirTree( racine,top );
            arrange(top);
        }
     
     
         void arrange(DefaultMutableTreeNode top)
         {
           int num = top.getChildCount();
            DefaultMutableTreeNode temp = new DefaultMutableTreeNode(racineName);
            DefaultMutableTreeNode child = new DefaultMutableTreeNode();
             for &#40;int i = 0 ; i <num; i++&#41;
            &#123;
              child =&#40;DefaultMutableTreeNode&#41; top.getNextNode&#40;&#41;;
              temp.add&#40;child&#41;;
            &#125;
     
     
            top.removeAllChildren&#40;&#41;;
     
             int i = 0;
             for &#40;int j = 0 ; j < num; j++&#41;
            &#123;
                child =&#40;DefaultMutableTreeNode&#41; temp.getChildAt&#40;i&#41;;
                if &#40;child.isLeaf&#40;&#41;&#41;
                   &#123;
                    top.add&#40;child&#41;;
                    &#125;
                else
                 i = i+1;
            &#125;
            i = 0;
            num = temp.getChildCount&#40;&#41;;
            for &#40;int j = 0 ; j < num; j++&#41;
            &#123;
                child =&#40;DefaultMutableTreeNode&#41; temp.getChildAt&#40;i&#41;;
               if &#40;!child.isLeaf&#40;&#41;&#41;
                   &#123;
                    arrange&#40;child&#41;;
                    top.add&#40;child&#41;;
                    &#125;
                else
                 i = i+1;
              &#125;
     
         &#125;
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
        private  void createAndShowGUI&#40;&#41; &#123;
            if &#40;useSystemLookAndFeel&#41; &#123;
                try &#123;
                    UIManager.setLookAndFeel&#40; UIManager.getSystemLookAndFeelClassName&#40;&#41;&#41;;
                    &#125; catch &#40;Exception e&#41; &#123;
                    System.err.println&#40;"Couldn't use system look and feel."&#41;;
                &#125;
            &#125;
     
     
     
            this.setOpaque&#40;true&#41;; //content panes must be opaque
            principalframe.setContentPane&#40;this&#41;;
            //principalframe.setIconImage&#40;img&#41;;
     
            //Display the window.
            principalframe.setSize&#40;500,300&#41;;
            System.out.println&#40;"la largeur de la frameprincipal"+this.getWidth&#40;&#41;&#41;;
            principalframe.setLocation&#40;&#40;int&#41;&#40;&#40;screenSize.width-principalframe.getWidth&#40;&#41;&#41;/2&#41; ,&#40;int&#41;&#40; &#40;screenSize.height-principalframe.getHeight&#40;&#41;&#41;/2&#41;&#41;;
            principalframe.setTitle&#40;"Décodeur"&#41;;
            principalframe.addWindowListener&#40;new WindowAdapter&#40;&#41; &#123;
            public void windowClosing&#40;WindowEvent e&#41; &#123;e.getWindow&#40;&#41;.dispose&#40;&#41;; System.exit&#40;1&#41;;&#125;
             &#125;&#41;;
            principalframe.setVisible&#40;true&#41;;
            System.out.println&#40;"Fin"&#41;;
        &#125;
     
        public void remplirTree&#40;File racine ,DefaultMutableTreeNode top&#41;
        &#123;
           if &#40; racine.isDirectory &#40; &#41; &#41;
                &#123;
                   File&#91;&#93; list = racine.listFiles&#40;&#41;;
                   if &#40; list.length != 0&#41;&#123;
                    for &#40; int i = 0; i < list.length; i++&#41;
                       &#123;
                          if &#40;list&#91;i&#93;.isDirectory&#40;&#41;&#41; 
                          &#123;
                            category = new DefaultMutableTreeNode&#40; list&#91;i&#93;.getName&#40;&#41;&#41;;
                            top.add&#40;category&#41;;
                          &#125;
                            else
                            category = top;
                            remplirTree&#40; list&#91;i&#93;,category &#41;;
                       &#125;
                    &#125;
                    else
                    &#123;
                      top.setAllowsChildren&#40;true&#41;;
                    &#125;
     
              &#125;
            else
               if &#40; racine.isFile&#40;&#41;&#41;
                 &#123;
                   book = new DefaultMutableTreeNode&#40;racine.getName&#40;&#41;&#41;;
                   book.setAllowsChildren&#40;false&#41;;
                   category.add&#40;book&#41;;
                 &#125;
        &#125;
     
     
     
     
     
     
        public String recupInfo&#40;File xmlFile&#41;
        &#123;
         String html = null;
         String name = null;
         String day = null;
         String firstname = null ;
     
         try&#123;
           XMLDocument root;
           DOMParser dp=new DOMParser&#40;&#41;;
           InputStream is = null;
           is = new FileInputStream&#40;xmlFile&#41;;
           root=XMLHelper.parse&#40;is,null&#41;;
           System.out.println&#40;"le fichier est bien parsé "&#41;;
           NodeList ndNom = root.getElementsByTagName&#40;"nom"&#41;;
           NodeList ndPrenom = root.getElementsByTagName&#40;"prenom"&#41;;
           NodeList ndDate = root.getElementsByTagName&#40;"date"&#41;;
           NodeList ndSymp = root.getElementsByTagName&#40;"principal"&#41;;
           System.out.println&#40;"apres apres"&#41;;
     
            if &#40;ndNom.getLength&#40;&#41; == 0 && ndPrenom.getLength&#40;&#41; == 0 && ndDate.getLength&#40;&#41; == 0&#41;
            &#123;
     
           System.out.println&#40;"les noeud null"&#41;;
            html = "Le fichier que vous avez selectionné ne porte aucune information sur le patient ni sur la date de la consultation.";
     
             &#125;
           else
           &#123;
           Node nodename = ndNom.item&#40;0&#41; ;
           name = nodename.getFirstChild&#40;&#41;.getNodeValue&#40;&#41;;
     
           Node nodedate = ndDate.item&#40;0&#41; ;
           day = nodedate.getFirstChild&#40;&#41;.getNodeValue&#40;&#41;;
     
           Node prenom = ndPrenom.item&#40;0&#41; ;
           firstname = prenom.getFirstChild&#40;&#41;.getNodeValue&#40;&#41;;
     
           System.out.println&#40;name +"  ; "+firstname+" ;  "+day&#41;;
           &#125;
     
           if &#40;name == null && firstname == null && day == null&#41;
           html = "Le fichier que vous avez selectionné ne porte aucune information sur le patient ni sur la date de la consultation. <br><br>La consultation traite les symptomes suivants &#58;";
           else
           html = "Le fichier que vous avez selectionné est du patient &#58;<br><b> <font color='2255LL'>   "+name+"  "+firstname+"</font></b>.<br>Il date du <b>"+day+" </b>. <br><br>La consultation traite les symptomes suivants &#58;";
     
           for &#40;int i =0 ; i<ndSymp.getLength&#40;&#41;;i++&#41;
           &#123;
           XMLElement symp_princ =&#40;XMLElement&#41;ndSymp.item&#40;i&#41; ;
           NamedNodeMap namedNodeM = symp_princ.getAttributes&#40;&#41;;
           String nomSymp=namedNodeM.item&#40;0&#41;.getNodeValue&#40;&#41;;
           html = html+"<li> <font color='6699cc'>"+nomSymp+"</font></li>";
           &#125;
           nomPatient = name;
           prenomPatient = firstname;
           date = day;
           //html = "Le fichier que vous avez selectionné est du patient &#58;<br><b>"+name+"  </b>  "+firstname+".<br>Il date du <b>"+day+" </b>. <br>La consultation traite les symptomes suivants &#58;<br>";
     
             is.close&#40;&#41;;
     
            &#125;catch &#40; Exception e &#41; &#123;&#125;
          return html;
        &#125;
     
     
     
        public void traite_affichage&#40;DefaultMutableTreeNode node&#41;
        &#123;
        if &#40;node!= null&#41;
           &#123;
           if &#40; node.isLeaf&#40;&#41; &#41;
            &#123;   String path = "" ;
                TreePath parentPath = tree.getSelectionPath&#40;&#41;;
     
                String chemin =node.toString&#40;&#41;;
                int cpt =0;
                for&#40; cpt = 0 ; cpt < parentPath.getPathCount&#40;&#41; ; cpt++&#41;
                &#123;
                   if &#40;path.compareTo&#40;""&#41;==1&#41;
                     path = &#40;String&#41;parentPath.getPathComponent&#40;cpt&#41;;
                   else
                    if &#40;parentPath.getPathComponent&#40;cpt&#41;!=null &#41;
                     path = path+"\\"+parentPath.getPathComponent&#40;cpt&#41;;
                &#125;
                System.out.println&#40;"le path  est  "+path&#41;;
                System.out.println&#40;"la variable chemin est   "+chemin&#41;;
                //htmlPane.setText&#40;"vous avez selectionné un fichier nommé &#58;"+node.toString&#40;&#41;+"\n \n le chemin du fichier est &#58; "+path&#41;;
                 ///////////////update//////////
                  top = new DefaultMutableTreeNode&#40;"e&#58;"&#41;;
                  createNodes&#40;top&#41;;
                  JTree tree2 = new JTree&#40;top,true&#41;;
                  treeView = new JScrollPane&#40;tree2&#41;;
                  tree2.updateUI&#40;&#41;;
                  treeView.updateUI&#40;&#41;;
                  ///////////////end update//////////
                  System.out.println&#40;"apres update"&#41;;
                File xmlfile = new File&#40;path&#41;;
                if &#40;xmlfile.exists&#40;&#41; && xmlfile.isFile&#40;&#41;&#41;
                &#123;
                  if &#40;path.endsWith&#40;".xml"&#41;&#41;
                  &#123;
     
                  decodeur.file = node.toString&#40;&#41;;
                  System.out.println&#40;"le fichier existe "&#41;;
                  String html = recupInfo&#40;xmlfile&#41;;
                  System.out.println&#40;"affichage html"+html&#41;;
     
                  htmlPane.setText&#40;html&#41;;
                  &#125;
                  else
                    if &#40;path.endsWith&#40;".htm"&#41;||path.endsWith&#40;".html"&#41;&#41;
                    &#123;
                      htmlPane.setText&#40;"c'est le fichier décodé du patient x &#40;à rechercher&#41;<br> qui date de l'année y"&#41;;
     
                    &#125;
                &#125;// end if xml file existe ...
                else
                  htmlPane.setText&#40;"Le repertoire que vous avez selectionné est un repertoire vide"&#41;;
              &#125;// end if
              else
              &#123;
                htmlPane.setText&#40;"vous avez selectiooné le repertoire nommé &#58; "+node.toString&#40;&#41;&#41;;
              &#125;
            &#125;//end if node!= null
        &#125;
     
     
     
        public static void main&#40;String&#91;&#93; args&#41; &#123;
     
           Explorer tr = new Explorer&#40;"C&#58;\\Decodeur\\Consultations"&#41;;
           tr.createAndShowGUI&#40;&#41;;
     
        &#125;
     
     
    &#125;
    ;-) cordialement

  9. #9
    Membre actif
    Inscrit en
    Juillet 2003
    Messages
    407
    Détails du profil
    Informations forums :
    Inscription : Juillet 2003
    Messages : 407
    Points : 252
    Points
    252
    Par défaut
    c résolu
    il fallait reconstruire le tree de nouveau :
    à chaque modification on lance le code suivant
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
                  String racineName = "e&#58;\\personnel";
                  top = new DefaultMutableTreeNode&#40;racineName&#41;;
                  createNodes&#40;top,racineName&#41;;
                  tree = new JTree&#40;top,true&#41;;
                  treeView = new JScrollPane&#40;tree&#41;;
                  tree.addTreeSelectionListener&#40;this&#41;;
                  tree.putClientProperty&#40;"JTree.lineStyle","Angled"&#41;;
                  tree.getSelectionModel&#40;&#41;.setSelectionMode&#40;TreeSelectionModel.SINGLE_TREE_SELECTION&#41;;
                 splitPane.setTopComponent&#40;treeView&#41;;
                  splitPane.setDividerLocation&#40;200&#41;;
                  principalframe.getContentPane&#40;&#41;.add&#40;splitPane&#41;;
                  principalframe.repaint&#40;&#41;;
    ;-) cordialement

  10. #10
    Membre émérite
    Avatar de Ioan
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    737
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 737
    Points : 2 999
    Points
    2 999
    Par défaut
    Bonjour,
    Une autre possibilité aurait été de travailler directement avec le modele du JTree. Voila un exemple de code qui permet de visualiser dans un JTree les fichiers de type htm,html,rtf,gif et jpg et de les afficher dans un JTextPane ou dans un JLabel. En plus de l'affichage, on peux supprimer un fichier donné (la mise a jour du tree se fait automatiquement, grâce à son modele). Je m'excuse d'avance , le code est un peu long et peu commenté, mais je pense qu'il est quand même interessant.
    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
     
    public class Explorateur extends JFrame implements TreeSelectionListener&#123;
    	//ATTRIBUTS_________________________________________________________________
    	private File root,currentFile;private TreeModel model;private JTree tree;
    	private JTextPane textPane;private JButton jbDelete;
    	private JLabel statut,labelImage;private JPanel panelAffichage;
    	private JScrollPane jspTree,jspAffichage;
    	//CONSTRUCTEURS_____________________________________________________________
    	public Explorateur&#40;String nomRepertoire&#41;&#123;
    		super&#40;"Explorateur"&#41;;
    		initRoot&#40;nomRepertoire&#41;;initTree&#40;&#41;;	
    		initAutresComposants&#40;&#41;;initFenetre&#40;&#41;;
    	&#125;
    	//METHODES__________________________________________________________________
    	//fonctions-----------------------------------------------------------------
    	public boolean acceptFile&#40;File file&#41;&#123;
    		if&#40;file==null||file.isDirectory&#40;&#41;&#41;&#123;return false;&#125;
    		String nom = file.getName&#40;&#41;;
    		if&#40;nom.endsWith&#40;".rtf"&#41;||nom.endsWith&#40;".htm"&#41;||nom.endsWith&#40;".html"&#41;
    			||nom.endsWith&#40;".gif"&#41;||nom.endsWith&#40;".jpg"&#41;&#41;&#123;return true;&#125;
    		return false;
    	&#125;
    	public boolean acceptFile&#40;&#41;&#123;return acceptFile&#40;currentFile&#41;;	&#125;
    	public boolean isImageFile&#40;&#41;&#123;
    		if&#40;currentFile==null&#41;&#123;return false;&#125;
    		String nom = currentFile.getName&#40;&#41;;
    		if&#40;nom.endsWith&#40;".gif"&#41;||nom.endsWith&#40;".jpg"&#41;&#41;&#123;return true;&#125;
    		return false;
    	&#125;
    	public boolean isTextFile&#40;&#41;&#123;
    		if&#40;currentFile==null&#41;&#123;return false;&#125;
    		String nom = currentFile.getName&#40;&#41;;
    		if&#40;nom.endsWith&#40;".rtf"&#41;||nom.endsWith&#40;".htm"&#41;||nom.endsWith&#40;".html"&#41;&#41;&#123;return true;&#125;
    		return false;
    	&#125;
    	public JWindow getFenetreChargement&#40;&#41;&#123;
    		JWindow w = new JWindow&#40;&#41;;
    		JLabel label = new JLabel&#40;"Chargement en cours ..."&#41;;label.setOpaque&#40;true&#41;;
    		label.setForeground&#40;Color.BLUE&#41;;label.setBorder&#40;BorderFactory.createLineBorder&#40;Color.BLUE&#41;&#41;;
    		w.getContentPane&#40;&#41;.add&#40;label&#41;;w.pack&#40;&#41;;w.setLocationRelativeTo&#40;null&#41;;
    		return w;	
    	&#125;
    	//procedures----------------------------------------------------------------
    	public void delete&#40;&#41;&#123;
    		if&#40;currentFile==null||currentFile.isDirectory&#40;&#41;&#41;&#123;return;&#125;
    		int commande = JOptionPane.showConfirmDialog&#40;this
    			,"Voulez vous vraiment supprimmer "+currentFile.getPath&#40;&#41;
    			,"Confirmez",JOptionPane.YES_NO_OPTION&#41;;
    		switch&#40;commande&#41;&#123;
    			case JOptionPane.YES_OPTION &#58; 
    				currentFile.delete&#40;&#41;;currentFile = null;
    				jspAffichage.setViewportView&#40;null&#41;;tree.updateUI&#40;&#41;;
    				break;
    			default &#58; return;		
    		&#125;		
    	&#125;
    	public void chargerTexte&#40;&#41;&#123;
    		try&#123;
    			if&#40;!acceptFile&#40;&#41;&#41;return;
    			if&#40;currentFile.getName&#40;&#41;.indexOf&#40;".htm"&#41;!=-1&#41;&#123;textPane.setContentType&#40;"text/html"&#41;;&#125;
    			else if&#40;currentFile.getName&#40;&#41;.endsWith&#40;".rtf"&#41;&#41;&#123;textPane.setContentType&#40;"text/rtf"&#41;;&#125;
    			textPane.setPage&#40;currentFile.toURL&#40;&#41;&#41;;textPane.setPreferredSize&#40;panelAffichage.getSize&#40;&#41;&#41;;
    			jspAffichage.setViewportView&#40;textPane&#41;;jspAffichage.getViewport&#40;&#41;.setViewSize&#40;textPane.getPreferredSize&#40;&#41;&#41;;
    		&#125;
    		catch&#40;Exception exc&#41;&#123;exc.printStackTrace&#40;&#41;;&#125;	
    	&#125;
    	public void chargerImage&#40;&#41;&#123;
    		try&#123;
    			ImageIcon imageIcon = new ImageIcon&#40;currentFile.getPath&#40;&#41;&#41;;
    			labelImage.setIcon&#40;imageIcon&#41;;jspAffichage.setViewportView&#40;labelImage&#41;;
    			jspAffichage.getViewport&#40;&#41;.setViewSize&#40;labelImage.getPreferredSize&#40;&#41;&#41;;
    		&#125;catch&#40;Exception exc&#41;&#123;exc.printStackTrace&#40;&#41;;&#125;
    	&#125;
    	public void afficherFichierTexte&#40;&#41;&#123;
    		Thread thread = new Thread&#40;&#41;&#123;
    			public void run&#40;&#41;&#123;
    				JWindow w = getFenetreChargement&#40;&#41;;w.show&#40;&#41;;
    				chargerTexte&#40;&#41;;w.dispose&#40;&#41;;
    			&#125;	
    		&#125;;
    		thread.start&#40;&#41;;	
    	&#125;
    	public void afficherFichierImage&#40;&#41;&#123;
    		Thread thread = new Thread&#40;&#41;&#123;
    			public void run&#40;&#41;&#123;
    				JWindow w = getFenetreChargement&#40;&#41;;w.show&#40;&#41;;
    				chargerImage&#40;&#41;;w.dispose&#40;&#41;;
    			&#125;	
    		&#125;;
    		thread.start&#40;&#41;;		
    	&#125;
    	//procedures TreeSelectionListener------------------------------------------
    	public void valueChanged&#40;TreeSelectionEvent e&#41;&#123;
    		TreePath path = e.getPath&#40;&#41;;jspAffichage.setViewportView&#40;null&#41;;
    		if&#40;e==null||path==null&#41;&#123;
    			currentFile=null;
    			statut.setText&#40;"Current file = null"&#41;;statut.setForeground&#40;Color.RED&#41;;
    			jbDelete.setEnabled&#40;false&#41;;return;
    		&#125;
    		currentFile = &#40;File&#41;path.getLastPathComponent&#40;&#41;;
    		statut.setText&#40;"Current file = "+currentFile.getPath&#40;&#41;&#41;;
    		if&#40;acceptFile&#40;&#41;&#41;&#123;
    			jbDelete.setEnabled&#40;true&#41;; statut.setForeground&#40;Color.BLUE&#41;;
    			if&#40;isImageFile&#40;&#41;&#41;&#123;afficherFichierImage&#40;&#41;;&#125;else if&#40;isTextFile&#40;&#41;&#41;&#123;afficherFichierTexte&#40;&#41;;&#125;
    		&#125;else&#123;
    			jbDelete.setEnabled&#40;false&#41;; statut.setForeground&#40;Color.RED&#41;;
    		&#125;
    	&#125;
    	//procedures d'initialisation-----------------------------------------------
    	public void initRoot&#40;String nomRepertoire&#41;&#123;
    		System.out.println&#40;"INIT ROOT"&#41;;
    		if&#40;nomRepertoire==null&#41;&#123;System.out.println&#40;"Erreur &#58; nom repertoire null"&#41;;System.exit&#40;0&#41;;		&#125;
    		root = new File&#40;nomRepertoire&#41;;	
    		if&#40;!root.exists&#40;&#41;&#41;&#123;System.out.println&#40;"Erreur &#58; "+nomRepertoire+" n'existe pas"&#41;;System.exit&#40;0&#41;;		&#125;
    		if&#40;!root.isDirectory&#40;&#41;&#41;&#123;System.out.println&#40;"Erreur &#58; "+nomRepertoire+" n'est pas un dossier"&#41;;System.exit&#40;0&#41;;		&#125;
    		currentFile = null;
    	&#125;
    	public void initTree&#40;&#41;&#123;
    		System.out.println&#40;"INIT TREE"&#41;;
    		System.out.println&#40;"->init modele"&#41;;
    		model = new TreeModel&#40;&#41;&#123;
    			 //methodes sur mesure
    			 public java.util.List getFichiers&#40;Object parent&#41;&#123;
    			 	File fileParent = &#40;File&#41;parent;
    			 	File&#91;&#93; fichiers = fileParent.listFiles&#40;new FileFilter&#40;&#41;&#123;
    			 		public boolean accept&#40;File file&#41;&#123;return acceptFile&#40;file&#41;||file.isDirectory&#40;&#41;;&#125;	
    			 	&#125;&#41;;
    			 	Arrays.sort&#40;fichiers,new Comparator&#40;&#41;&#123;
    			 		public int compare&#40;Object o1,Object o2&#41;&#123;
    			 			File f1 = &#40;File&#41;o1;File f2 = &#40;File&#41;o2;
    			 			boolean dirf1 = f1.isDirectory&#40;&#41;;boolean dirf2 = f2.isDirectory&#40;&#41;;
    			 			if&#40;dirf1&&!dirf2&#41;&#123;return -1;&#125;if&#40;!dirf1&&dirf2&#41;&#123;return 1;&#125;
    			 			return f1.getPath&#40;&#41;.compareTo&#40;f2.getPath&#40;&#41;&#41;;
    			 		&#125;	
    			 	&#125;&#41;;
    			 	return	Arrays.asList&#40;fichiers&#41;;
    			 &#125;
    			 //surcharge de certaines methodes
    			 public Object getRoot&#40;&#41;&#123;return root;&#125;
    			 public Object getChild&#40;Object parent, int index&#41;&#123;return getFichiers&#40;parent&#41;.get&#40;index&#41;;&#125; 
    			 public int getChildCount&#40;Object parent&#41;&#123;return getFichiers&#40;parent&#41;.size&#40;&#41;;&#125; 
    			 public int getIndexOfChild&#40;Object parent, Object child&#41;&#123;return getFichiers&#40;parent&#41;.indexOf&#40;child&#41;;&#125; 
    			 public boolean isLeaf&#40;Object node&#41;&#123;
    			 	File f = &#40;File&#41;node;if&#40;!f.isDirectory&#40;&#41;&#41;&#123;return true;&#125;
    			 	return false;
    			 &#125;  
    			 public void valueForPathChanged&#40;TreePath path, Object newValue&#41;&#123;&#125;  
    			 public void addTreeModelListener&#40;TreeModelListener l&#41;&#123;&#125;  
    			 public void removeTreeModelListener&#40;TreeModelListener l&#41;&#123;&#125;  	
    		&#125;;
    		System.out.println&#40;"->init tree"&#41;;
    		tree = new JTree&#40;model&#41;;tree.setEditable&#40;false&#41;;
    		tree.getSelectionModel&#40;&#41;.setSelectionMode&#40;TreeSelectionModel.SINGLE_TREE_SELECTION&#41;; 
    		tree.addTreeSelectionListener&#40;this&#41;;tree.putClientProperty&#40;"JTree.lineStyle","Angled"&#41;; 
            System.out.println&#40;"->init renderer"&#41;;
            tree.setCellRenderer&#40;new DefaultTreeCellRenderer&#40;&#41;&#123;
            	public Component getTreeCellRendererComponent&#40;JTree tree,Object value
            			,boolean selected,boolean expanded
            			,boolean leaf,int row,boolean hasFocus&#41;&#123;
            		JLabel label = &#40;JLabel&#41;super.getTreeCellRendererComponent&#40;tree,value,selected,expanded,leaf,row,hasFocus&#41;;
            		File fichier = &#40;File&#41;value;label.setText&#40;fichier.getName&#40;&#41;&#41;;
            		if&#40;fichier.isDirectory&#40;&#41;&#41;&#123;label.setForeground&#40;Color.BLACK&#41;;&#125;
            		else if&#40;acceptFile&#40;fichier&#41;&#41;&#123;label.setForeground&#40;Color.BLUE&#41;;&#125;
            		else&#123;label.setForeground&#40;Color.RED&#41;;&#125;
            		return label;				
            	&#125;  	
            &#125;&#41;;
            tree.addTreeExpansionListener&#40;new TreeExpansionListener&#40;&#41;&#123;
    			public void treeCollapsed&#40;TreeExpansionEvent event&#41;&#123;jspTree.getViewport&#40;&#41;.setViewSize&#40;tree.getPreferredScrollableViewportSize&#40;&#41;&#41;;&#125; 
            	public void treeExpanded&#40;TreeExpansionEvent event&#41;&#123;jspTree.getViewport&#40;&#41;.setViewSize&#40;tree.getPreferredScrollableViewportSize&#40;&#41;&#41;;&#125;	
    		&#125;&#41;;
    	&#125;
    	public void initAutresComposants&#40;&#41;&#123;
    		System.out.println&#40;"INIT AUTRES COMPOSANTS GRAPHIQUES"&#41;;
    		System.out.println&#40;"->init pane"&#41;;
    		textPane = new JTextPane&#40;&#41;;textPane.setEditable&#40;false&#41;;
    		System.out.println&#40;"->init label image"&#41;;labelImage = new JLabel&#40;&#41;;
    		System.out.println&#40;"->init bouton"&#41;;
    		jbDelete = new JButton&#40;"Supprimmer"&#41;;jbDelete.setEnabled&#40;false&#41;;
    		jbDelete.addActionListener&#40;new ActionListener&#40;&#41;&#123;public void actionPerformed&#40;ActionEvent ae&#41;&#123;delete&#40;&#41;;&#125;	&#125;&#41;;	
    		System.out.println&#40;"->init barre de statut"&#41;;
    		statut = new JLabel&#40;"Current file = null"&#41;;statut.setOpaque&#40;true&#41;;
    		statut.setForeground&#40;Color.RED&#41;;statut.setBorder&#40;BorderFactory.createLineBorder&#40;Color.BLUE&#41;&#41;;
    	&#125;
    	public void initFenetre&#40;&#41;&#123;
    		System.out.println&#40;"INIT FENETRE"&#41;;
    		System.out.println&#40;"->init panneaux intermediaires"&#41;;
    		panelAffichage = new JPanel&#40;&#41;;
    		panelAffichage.setPreferredSize&#40;new Dimension&#40;500,500&#41;&#41;;
    		JPanel panelOuest = new JPanel&#40;new BorderLayout&#40;&#41;&#41;;
    		panelOuest.setPreferredSize&#40;new Dimension&#40;300,500&#41;&#41;;
    		System.out.println&#40;"->init jsp"&#41;;
    		jspTree = new JScrollPane&#40;tree&#41;;jspAffichage = new JScrollPane&#40;&#41;;
    		jspAffichage.setPreferredSize&#40;panelAffichage.getPreferredSize&#40;&#41;&#41;;
    		jspAffichage.setBorder&#40;BorderFactory.createTitledBorder&#40;"Zone d'affichage"&#41;&#41;;
    		System.out.println&#40;"->placement des composants"&#41;;
    		panelOuest.add&#40;jspTree,BorderLayout.CENTER&#41;;panelOuest.add&#40;jbDelete,BorderLayout.SOUTH&#41;;
    		panelAffichage.add&#40;jspAffichage&#41;;
    		getContentPane&#40;&#41;.add&#40;panelAffichage,BorderLayout.CENTER&#41;;
    		getContentPane&#40;&#41;.add&#40;panelOuest,BorderLayout.WEST&#41;;
    		getContentPane&#40;&#41;.add&#40;statut,BorderLayout.SOUTH&#41;;
    		System.out.println&#40;"->finitions"&#41;;
    		setDefaultCloseOperation&#40;JFrame.EXIT_ON_CLOSE&#41;;pack&#40;&#41;;setLocationRelativeTo&#40;null&#41;;setVisible&#40;true&#41;;	
    	&#125;
    	//MAIN______________________________________________________________________
    	public static void main&#40;String&#91;&#93; args&#41;&#123;new Explorateur&#40;"c&#58;\\ioan"&#41;;&#125;
    &#125;
    Voila, voila ....
    @+
    Les FAQs Java, J2EE, JDBC, Struts > Les cours > Le Forum Java.
    Merci de respecter les règles du club.
    Mon blog : quelques news sur Java, Linux et le monde de l'Open Source.

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

Discussions similaires

  1. [MFC] Problème de rafraichissement,
    Par pykoon dans le forum MFC
    Réponses: 1
    Dernier message: 27/04/2005, 08h21
  2. Problème de rafraichissement.
    Par beyo dans le forum ASP
    Réponses: 5
    Dernier message: 18/03/2005, 17h27
  3. [JTree] Problème d'ouverture de chemin dans un JTree
    Par antares24 dans le forum Composants
    Réponses: 2
    Dernier message: 11/03/2005, 09h18
  4. [SWING] Problème de rafraichissement
    Par david71 dans le forum AWT/Swing
    Réponses: 3
    Dernier message: 24/05/2004, 16h38
  5. Toujours un problème de rafraichissement de DBGrid
    Par tripper.dim dans le forum C++Builder
    Réponses: 4
    Dernier message: 09/12/2002, 14h15

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