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 :

Comprendre la structure JTree


Sujet :

Composants Java

  1. #1
    Candidat au Club
    Homme Profil pro
    Etudiant
    Inscrit en
    Octobre 2017
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Côtes d'Armor (Bretagne)

    Informations professionnelles :
    Activité : Etudiant

    Informations forums :
    Inscription : Octobre 2017
    Messages : 2
    Points : 2
    Points
    2
    Par défaut Comprendre la structure JTree
    Bonjour,


    Je viens de récupérer un code sur les JTree mais je ne comprend pas bien la structure de l'IHM.

    Je souhaite afficher 2 arbres sur une interface séparée en 2, avec plusieurs boutons pour ajouter, supprimer ou modifier des éléments.

    Le problème c'est que je ne comprend pas quel élément je dois manipuler pour avoir 2 JTree différents, ni ce que je dois créer pour séparer les arbres.

    Voici mon code actuel (Attention j'ai enlevé la condition qui limite le nombre de sous fichiers à parcourir) :

    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
    //CTRL + SHIFT + O pour générer les imports nécessaires
    public class Fenetre extends JFrame {
      private JTree arbre;
      private DefaultMutableTreeNode racine;
      private DefaultTreeModel model;
      private JButton bouton = new JButton("Ajouter");
     
      public Fenetre(){
        this.setSize(600, 700);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
        this.setTitle("JTree");
        //On invoque la méthode de construction de l'arbre
     
        initTree();
        bouton.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event) {
            if(arbre.getLastSelectedPathComponent() != null){
              JOptionPane jop = new JOptionPane();
              String nodeName = jop.showInputDialog("Saisir un nom de noeud");
     
              if(nodeName != null && !nodeName.trim().equals("")){
                DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)arbre.getLastSelectedPathComponent();
                DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(nodeName);
                parentNode.add(childNode);
                model.insertNodeInto(childNode, parentNode, parentNode.getChildCount()-1);
                model.nodeChanged(parentNode);
              }
            }
            else{
              System.out.println("Aucune sélection !");
            }
          }
        });
        this.getContentPane().add(bouton, BorderLayout.SOUTH);
        this.setVisible(true);
      }
     
      private void initTree(){
            File dir = new File("D:\\Bureau");
            this.racine = listFile(dir,new DefaultMutableTreeNode(dir));
            // On crée, avec notre hiérarchie, un arbre
            arbre = new JTree(this.racine);
     
            // Que nous plaçons sur le ContentPane de notre JFrame à l'aide d'un
            // scroll
            this.getContentPane().add(new JScrollPane(arbre));
            this.model = new DefaultTreeModel(this.racine);
            arbre.setModel(model);
            arbre.setRootVisible(false);
            arbre.setEditable(true);
            arbre.addTreeSelectionListener(new TreeSelectionListener(){
     
              public void valueChanged(TreeSelectionEvent event) {
                if(arbre.getLastSelectedPathComponent() != null){
                  //La méthode getPath retourne un objet TreePath
                  System.out.println(getAbsolutePath(event.getPath()));
                }
              }
     
              private String getAbsolutePath(TreePath treePath){
                String str = "";
                //On balaie le contenu de l'objet TreePath
                for(Object name : treePath.getPath()){
                  //Si l'objet a un nom, on l'ajoute au chemin
                  if(name.toString() != null)
                    str += name.toString();
                }
                return str;
              }
            });
     
            arbre.getModel().addTreeModelListener(new TreeModelListener() {
              public void treeNodesChanged(TreeModelEvent evt) {
                System.out.println("Changement dans l'arbre");
                Object[] listNoeuds = evt.getChildren();
                int[] listIndices = evt.getChildIndices();
                for (int i = 0; i < listNoeuds.length; i++) {
                  System.out.println("Index " + listIndices[i] + ", noeud déclencheur : " + listNoeuds[i]);
                }
              }
              public void treeNodesInserted(TreeModelEvent event) {
                System.out.println("Un noeud a été inséré !");
              }
              public void treeNodesRemoved(TreeModelEvent event) {
                System.out.println("Un noeud a été retiré !");
              }
              public void treeStructureChanged(TreeModelEvent event) {
                System.out.println("La structure d'un noeud a changé !");
              }
            });
          }
     
      private DefaultMutableTreeNode listFile(File file, DefaultMutableTreeNode node){
        int count = 0;
        if(file.isFile())
          return new DefaultMutableTreeNode(file.getName());
        else{
          File[] list = file.listFiles();
          if(list == null)
            return new DefaultMutableTreeNode(file.getName());
     
          for(File nom : list){
              DefaultMutableTreeNode subNode;
              if(nom.isDirectory()){
                subNode = new DefaultMutableTreeNode(nom.getName()+"\\");
                node.add(this.listFile(nom, subNode));
              }else{
                subNode = new DefaultMutableTreeNode(nom.getName());
              }
              node.add(subNode);
     
          }
          return node;
        }
      }
     
      public static void main(String[] args){
        //Nous allons créer des fenêtres avec des look and feel différents
        //Cette instruction permet de récupérer tous les look and feel du système
     
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (InstantiationException e) {}
        catch (ClassNotFoundException e) {}
        catch (UnsupportedLookAndFeelException e) {}
        catch (IllegalAccessException e) {}
        Fenetre fen = new Fenetre();
     
      }
    }

    Merci !

  2. #2
    Candidat au Club
    Homme Profil pro
    Etudiant
    Inscrit en
    Octobre 2017
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Côtes d'Armor (Bretagne)

    Informations professionnelles :
    Activité : Etudiant

    Informations forums :
    Inscription : Octobre 2017
    Messages : 2
    Points : 2
    Points
    2
    Par défaut
    Finalement j'ai réussi à comprendre la structure et je l'ai modifiée avec un "GridPane" qui contient les 2 JTree.

    Pour ceux que ça intéresse, je vous met mon code :

    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
    //CTRL + SHIFT + O pour générer les imports nécessaires
    public class Fenetre extends JFrame {
      private JTree arbre;
      private JTree arbre2;
      private DefaultMutableTreeNode racine;
      private DefaultMutableTreeNode racine2;
      private DefaultTreeModel model;
      private DefaultTreeModel model2;
      private JButton bouton = new JButton("Ajouter");
      private JPanel panel_1 = new JPanel();
     
      public Fenetre(){
    	this.setBounds(100, 100, 450, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
        this.setTitle("JTree");
        //On invoque la méthode de construction de l'arbre
     
        JPanel panel = new JPanel();
    	this.getContentPane().add(panel, BorderLayout.SOUTH);
     
    	panel.add(bouton);
     
    	JButton btnModifier = new JButton("Modifier");
    	panel.add(btnModifier);
     
    	JButton btnSupprimer = new JButton("Supprimer");
    	panel.add(btnSupprimer);
     
    	this.getContentPane().add(panel_1, BorderLayout.CENTER);
    	panel_1.setLayout(new GridLayout(1, 0, 0, 0));
     
        initTree();
        bouton.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event) {
            if(arbre.getLastSelectedPathComponent() != null){                  
              JOptionPane jop = new JOptionPane();
              String nodeName = jop.showInputDialog("Saisir un nom de noeud");
     
              if(nodeName != null && !nodeName.trim().equals("")){                  
                DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)arbre.getLastSelectedPathComponent();
                DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(nodeName);
                parentNode.add(childNode);
                model.insertNodeInto(childNode, parentNode, parentNode.getChildCount()-1);
                model.nodeChanged(parentNode);                  
              }               
            }
            else{
              System.out.println("Aucune sélection !");
            }
          }
        });
        this.setVisible(true);
      }
     
      private void initTree(){
    	    File dir = new File("D:\\Bureau\\Dossier1");
    	    this.racine = listFile(dir,new DefaultMutableTreeNode(dir));
    	    // On crée, avec notre hiérarchie, un arbre
    	    arbre = new JTree(this.racine);
     
    	    File dir2 = new File("D:\\Bureau\\Dossier2");
    	    this.racine2 = listFile(dir2,new DefaultMutableTreeNode(dir2));
    	    arbre2 = new JTree(this.racine2);
     
    	    // Que nous plaçons sur le ContentPane de notre JFrame à l'aide d'un
    	    // scroll
    //	    splitPane.setLeftComponent(new JScrollPane(arbre));
    //	    splitPane.setRightComponent(new JScrollPane(arbre2));
     
    		arbre.setBorder(new LineBorder(new Color(0, 0, 0)));
    		arbre.setEnabled(false);
    		panel_1.add(arbre);
     
    		arbre2.setBorder(new LineBorder(new Color(0, 0, 0)));
    		panel_1.add(arbre2);
     
     
     
    	    this.model = new DefaultTreeModel(this.racine);
    	    arbre.setModel(model);
    	    arbre.setRootVisible(false);
    	    arbre.setEditable(true);
    	    arbre.addTreeSelectionListener(new TreeSelectionListener(){
     
        	  public void valueChanged(TreeSelectionEvent event) {
        	    if(arbre.getLastSelectedPathComponent() != null){
        	      //La méthode getPath retourne un objet TreePath
        	      System.out.println(getAbsolutePath(event.getPath()));
        	    }
        	  }
     
        	  private String getAbsolutePath(TreePath treePath){
        	    String str = "";
        	    //On balaie le contenu de l'objet TreePath
        	    for(Object name : treePath.getPath()){
        	      //Si l'objet a un nom, on l'ajoute au chemin
        	      if(name.toString() != null)
        	        str += name.toString();
        	    }
        	    return str;
        	  }
        	});
     
    	    this.model2 = new DefaultTreeModel(this.racine2);
    	    arbre2.setModel(model2);
    	    arbre2.setRootVisible(false);
    	    arbre2.setEditable(true);
    	    arbre2.addTreeSelectionListener(new TreeSelectionListener(){
     
    	    	  public void valueChanged(TreeSelectionEvent event) {
    	    	    if(arbre2.getLastSelectedPathComponent() != null){
    	    	      //La méthode getPath retourne un objet TreePath
    	    	      System.out.println(getAbsolutePath(event.getPath()));
    	    	    }
    	    	  }
     
    	    	  private String getAbsolutePath(TreePath treePath){
    	    	    String str = "";
    	    	    //On balaie le contenu de l'objet TreePath
    	    	    for(Object name : treePath.getPath()){
    	    	      //Si l'objet a un nom, on l'ajoute au chemin
    	    	      if(name.toString() != null)
    	    	        str += name.toString();
    	    	    }
    	    	    return str;
    	    	  }
    	    	});
     
    	    arbre.getModel().addTreeModelListener(new TreeModelListener() {
    	      public void treeNodesChanged(TreeModelEvent evt) {
    	        System.out.println("Changement dans l'arbre");
    	        Object[] listNoeuds = evt.getChildren();
    	        int[] listIndices = evt.getChildIndices();
    	        for (int i = 0; i < listNoeuds.length; i++) {
    	          System.out.println("Index " + listIndices[i] + ", noeud déclencheur : " + listNoeuds[i]);
    	        }
    	      }   
    	      public void treeNodesInserted(TreeModelEvent event) {
    	        System.out.println("Un noeud a été inséré !");            
    	      }
    	      public void treeNodesRemoved(TreeModelEvent event) {
    	        System.out.println("Un noeud a été retiré !");
    	      }
    	      public void treeStructureChanged(TreeModelEvent event) {
    	        System.out.println("La structure d'un noeud a changé !");
    	      }
    	    });
     
    	    arbre2.getModel().addTreeModelListener(new TreeModelListener() {
    	      public void treeNodesChanged(TreeModelEvent evt) {
    	        System.out.println("Changement dans l'arbre");
    	        Object[] listNoeuds = evt.getChildren();
    	        int[] listIndices = evt.getChildIndices();
    	        for (int i = 0; i < listNoeuds.length; i++) {
    	          System.out.println("Index " + listIndices[i] + ", noeud déclencheur : " + listNoeuds[i]);
    	        }
    	      }   
    	      public void treeNodesInserted(TreeModelEvent event) {
    	        System.out.println("Un noeud a été inséré !");            
    	      }
    	      public void treeNodesRemoved(TreeModelEvent event) {
    	        System.out.println("Un noeud a été retiré !");
    	      }
    	      public void treeStructureChanged(TreeModelEvent event) {
    	        System.out.println("La structure d'un noeud a changé !");
    	      }
    	    });
    	  }
     
      private DefaultMutableTreeNode listFile(File file, DefaultMutableTreeNode node){
        int count = 0;      
        if(file.isFile())
          return new DefaultMutableTreeNode(file.getName());
        else{
          File[] list = file.listFiles();
          if(list == null)
            return new DefaultMutableTreeNode(file.getName());
     
          for(File nom : list){
              DefaultMutableTreeNode subNode;
              if(nom.isDirectory()){
                subNode = new DefaultMutableTreeNode(nom.getName()+"\\");
                node.add(this.listFile(nom, subNode));
              }else{
                subNode = new DefaultMutableTreeNode(nom.getName());
              }
              node.add(subNode);
     
          }
          return node;
        }
      }
     
      public static void main(String[] args){
        //Nous allons créer des fenêtres avec des look and feel différents 
        //Cette instruction permet de récupérer tous les look and feel du système
     
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (InstantiationException e) {}
        catch (ClassNotFoundException e) {}
        catch (UnsupportedLookAndFeelException e) {}
        catch (IllegalAccessException e) {}
        Fenetre fen = new Fenetre();
     
      }
    }
    Ce qui donne :

    Nom : Capture.PNG
Affichages : 82
Taille : 8,2 Ko

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

Discussions similaires

  1. Réponses: 10
    Dernier message: 20/06/2014, 12h11
  2. [Toutes versions] Comprendre la Structure d'une adresse mail.
    Par JOHN14 dans le forum Outlook
    Réponses: 0
    Dernier message: 22/05/2014, 12h20
  3. Comprendre la structure d'un jeu
    Par Youille dans le forum Développement 2D, 3D et Jeux
    Réponses: 5
    Dernier message: 16/02/2012, 12h19
  4. [débutant] [JTree] Comprendre une sélection
    Par calogerogigante dans le forum Composants
    Réponses: 4
    Dernier message: 26/10/2005, 15h34

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