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] Drag and drop


Sujet :

Composants Java

  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Mai 2004
    Messages
    167
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2004
    Messages : 167
    Par défaut [JTree] Drag and drop
    Je cherche a réaliser un drag and drop dans un JTree
    (En fait, je cherche juste a permettre le déplacement d'un noeud vers un autre emplacement)...seulement je me rend compte que faire un drag and drop avec un JTree c'est pas vraiment évident...
    Quelqu'un aurait-il une piste?
    Du moins comment faut-il s'y prendre?
    Merci d'avance!

  2. #2
    Membre éclairé Avatar de biozaxx
    Profil pro
    Inscrit en
    Août 2004
    Messages
    403
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2004
    Messages : 403
    Par défaut
    il me semble qu'on en a déja parlé plusieurs fois sur le forum

    en tout cas tu devrais aller voir ici
    http://www.javaworld.com/javaworld/javatips/jw-javatip97.html

    et ici
    http://www.javaworld.com/javaworld/javatips/jw-javatip114.html

    ca devrait t'aider a demarrer

    @+

  3. #3
    Membre éclairé Avatar de biozaxx
    Profil pro
    Inscrit en
    Août 2004
    Messages
    403
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2004
    Messages : 403
    Par défaut
    il y a egalement un tutorial sur le site de sun:
    http://java.sun.com/products/jfc/tsc/articles/dragndrop/

    et un sur le forum , sur une jtable soit mais ca reste du swing
    http://gfx.developpez.com/tutoriel/java/swing/drag/

  4. #4
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 904
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 904
    Billets dans le blog
    54
    Par défaut
    Un truc dans ce genre, qui permet aussi bien de deplacer des noeuds dans un arbre que de "dropper" la chaine de texte du noeud selectionne dans Word par exempe :

    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
     
    package test;
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
     
    /**
     * <p>Title: </p>
     *
     * <p>Description: </p>
     *
     * <p>Copyright: Copyright (c) 2005</p>
     *
     * <p>Company: </p>
     *
     * @author not attributable
     * @version 1.0
     */
    class Test {
      public Test() {
      }
     
      public static void main(String ...args) {
        DefaultTreeModel treeModel = createTreeModel();
        JTree tree = new JTree(treeModel);
        TreeSelectionModel treeSelectionModel = new DefaultTreeSelectionModel();
        treeSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.setSelectionModel(treeSelectionModel);
        tree.setDragEnabled(true);
        tree.setTransferHandler(new TreeTransfertHandler());
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(new JScrollPane(tree));
        frame.setSize(400, 300);
        frame.setVisible(true);
      }
     
      private static DefaultTreeModel createTreeModel() {
        DefaultMutableTreeNode root = createTreeNode(null, 5, 0);
        DefaultTreeModel result = new DefaultTreeModel(root);
        return result;
      }
     
      private static DefaultMutableTreeNode createTreeNode(DefaultMutableTreeNode parent, int level, int index) {
        if (level == 0) {
          return null;
        }
        DefaultMutableTreeNode node = new DefaultMutableTreeNode();
        StringBuilder buffer = new StringBuilder();
        if (parent != null) {
          buffer.append(parent.getUserObject());
          buffer.append("-");
        }
        buffer.append(index);
        String name = buffer.toString();
        node.setUserObject(name);
        level--;
        for (int i = 0; i < level; i++) {
          DefaultMutableTreeNode child = createTreeNode(node, level, i);
          if (child != null) {
            node.add(child);
          }
        }
        return node;
      }
    }
    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
     
    package test;
     
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.tree.*;
     
    /**
     * <p>Title: </p>
     *
     * <p>Description: </p>
     *
     * <p>Copyright: Copyright (c) 2005</p>
     *
     * <p>Company: </p>
     *
     * @author not attributable
     * @version 1.0
     */
    class TreeTransfertHandler extends TransferHandler {
      /** Last imported tree node.
       */
      private DefaultMutableTreeNode importedNode = null;
     
      /** Creates a new instance.
       */
      public TreeTransfertHandler() {
      }
     
     
      /** {@inheritDoc}
       * <BR>As of Java 1.4.x and 5.0 this method does not work properly (see bug <A HREF="http://developer.java.sun.com/developer/bugParade/bugs/4816922.html">#4816922</A> at Sun's web site).
       */
      @Override public Icon getVisualRepresentation(Transferable t) {
        return super.getVisualRepresentation(t);
      }
     
      /** {@inheritDoc}
       */
      @Override protected Transferable createTransferable(JComponent component) {
        String entity = exportEntity(component);
        // We could use a better transferable that could handle several dataflavors (text+image+treePath to node+....) at once.
        // So far this one is good for this TransferHandler and to ANY (including non-Java) app that can receive the STRING_FLAVOR.
        return new StringSelection(entity);
      }
     
      /** {@inheritDoc}
       */
      @Override protected void exportDone(JComponent c, Transferable data, int action) {
        cleanup(c, action == MOVE);
      }
     
      /////////////////////////////////
      // TransferHelper overloading. //
      /////////////////////////////////
     
      /** {@inheritDoc}
       */
      @Override public int getSourceActions(JComponent component) {
        JTree tree = (JTree) component;
        Object lastPathComponent = tree.getSelectionPath().getLastPathComponent();
        if (lastPathComponent instanceof DefaultMutableTreeNode) {
          DefaultMutableTreeNode node = (DefaultMutableTreeNode) lastPathComponent;
          Object obj = node.getUserObject();
          if (obj instanceof String) {
            return COPY_OR_MOVE;
          }
        }
        return NONE;
      }
     
      /** {@inheritDoc}
       */
      @Override public boolean canImport(JComponent component, DataFlavor[] flavors) {
        for (DataFlavor f : flavors) {
          // We can only import STRING_FLAVOR (plain text) so far.
          // We may add additional data flavors here in the future.
          if (DataFlavor.stringFlavor.equals(f)) {
            return true;
          }
        }
        return false;
      }
     
      /** {@inheritDoc}
       */
      @Override public boolean importData(JComponent component, Transferable t) {
        if (canImport(component, t.getTransferDataFlavors())) {
          try {
            // Remember as of now, we can only deal with STRING_FLAVOR.
            String text = (String) t.getTransferData(DataFlavor.stringFlavor);
            // We cheat, normally we should look into the tree for the proper node.
            // We could export the tree path to the node as a custom data flavor.
            // We have to test this when doing DnD with 2 different trees.
            return importEntity((JTree) component, importedNode);
          }
          catch (UnsupportedFlavorException ufe) {
            System.err.println(ufe);
          }
          catch (IOException ioe) {
            System.err.println(ioe);
          }
        }
        return false;
      }
     
      /////////////////////////
      // Convenient methods. //
      /////////////////////////
     
      /** Exports an entity from a component.
       * @param component The source component.
       * @return The entity to be exported.
       */
      public String exportEntity(JComponent component) {
        JTree tree = (JTree) component;
        Object lastPathComponent = tree.getSelectionPath().getLastPathComponent();
        if (lastPathComponent instanceof DefaultMutableTreeNode) {
          DefaultMutableTreeNode node = (DefaultMutableTreeNode) lastPathComponent;
          Object obj = node.getUserObject();
          if (obj instanceof String) {
            importedNode = node;
            return (String) obj;
          }
        }
        return null;
      }
     
      /** Imports a string to a component.
       * @param component The target component.
       * @param importedNode The node to import.
       * @return <code>True</code> if import was successfull, <code>false</code> otherwise.
       */
      public boolean importEntity(JComponent component, DefaultMutableTreeNode importedNode) {
        JTree tree = (JTree) component;
        Object lastPathComponent = tree.getSelectionPath().getLastPathComponent();
        if (lastPathComponent instanceof DefaultMutableTreeNode) {
          DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode) lastPathComponent;
          TreeNode rootNode = targetNode.getRoot();
          Enumeration ancestorEnumeration = targetNode.pathFromAncestorEnumeration(rootNode);
          // Verify we do not try to move the node to one of its sub-nodes.
          while (ancestorEnumeration.hasMoreElements()) {
            DefaultMutableTreeNode ancestorNode = (DefaultMutableTreeNode) ancestorEnumeration.nextElement();
            if (ancestorNode.equals(importedNode)) {
              System.err.println("Cannot import " + importedNode + " because " + ancestorNode + " is part of the path from " + targetNode + " to " + rootNode);
              return false;
            }
          }
          DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
          // Create a copy of the node structure.
          DefaultMutableTreeNode nodeCopy = duplicateNodeStructure(importedNode);
          model.insertNodeInto(nodeCopy, targetNode, 0);
          return true;
        }
        return false;
      }
     
      /** Cleanup after export.
       * @param component The source component.
       * @param remove <CODE>True</CODE> if the selection should be removed from the component; <CODE>false</CODE> otherwise.
       */
      protected void cleanup(JComponent component, boolean remove) {
        JTree tree = (JTree) component;
        // Remove string node from parent node.
        if (remove) {
          DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
          model.removeNodeFromParent(importedNode);
        }
        // Clean references.
        importedNode = null;
      }
     
      /** Duplicate a node structure.
       * @param sourceNode The source node.
       * @return A copy of the given node and all its sub-nodes.
       */
      private DefaultMutableTreeNode duplicateNodeStructure(DefaultMutableTreeNode sourceNode) {
        if (sourceNode == null) {
          return null;
        }
        DefaultMutableTreeNode result = new DefaultMutableTreeNode(sourceNode.getUserObject());
        Enumeration childrenEnumeration = sourceNode.children();
        while (childrenEnumeration.hasMoreElements()) {
          DefaultMutableTreeNode child = duplicateNodeStructure((DefaultMutableTreeNode) childrenEnumeration.nextElement());
          result.add(child);
        }
        return result;
      }
    }
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  5. #5
    Gfx
    Gfx est déconnecté
    Expert confirmé
    Avatar de Gfx
    Inscrit en
    Mai 2005
    Messages
    1 770
    Détails du profil
    Informations personnelles :
    Âge : 43

    Informations forums :
    Inscription : Mai 2005
    Messages : 1 770
    Par défaut
    On a fait une demo a JavaOne 2005 qui parle du drag and drop dans un arbre.

    En PDF : http://developers.sun.com/learning/javaoneonline/2005/desktop/TS-3605.pdf
    En flash avec les slides et la piste audio : http://developers.sun.com/learning/javaoneonline/sessions/2005/TS-3605/index.html

  6. #6
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 904
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 904
    Billets dans le blog
    54
    Par défaut
    Effectivement le code du handler a l'air plus simple/court. Ah c'est bien ca de pouvoir specifier le mode de drop dans l'arbre (vivement la version finale de Java 6).

    EDIT - je viens de jeter un coup d'oeuil a la javadoc de Mustang c'est vrai que les classe TransferHandler.TransferInfo et TransferHandler.DropLocation semblent bien pratiques.

    Note : la javadoc de la methode TransferHandler.shouldIndicate() n'indique pas qu'elle a ete rajoutee dans la 1.6
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  7. #7
    Gfx
    Gfx est déconnecté
    Expert confirmé
    Avatar de Gfx
    Inscrit en
    Mai 2005
    Messages
    1 770
    Détails du profil
    Informations personnelles :
    Âge : 43

    Informations forums :
    Inscription : Mai 2005
    Messages : 1 770
    Par défaut
    Ca permet de faire cet effet lors d'un drag :




    [/img]

  8. #8
    Membre confirmé
    Profil pro
    Inscrit en
    Mai 2004
    Messages
    167
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2004
    Messages : 167
    Par défaut
    Je vous remercie pour toutes vos contributions...
    Je vais regarder attentivement tout ca...
    Merci encore!

Discussions similaires

  1. (jlist,jtree) drag and drop entre 2 jlist vers un jtree
    Par olivier57b dans le forum Composants
    Réponses: 0
    Dernier message: 17/04/2012, 16h20
  2. Drag And Drop Jtree
    Par mkl78 dans le forum Composants
    Réponses: 3
    Dernier message: 29/06/2007, 13h40
  3. Drag and Drop entre 2 JTree
    Par Lebas dans le forum Composants
    Réponses: 1
    Dernier message: 07/02/2007, 11h59
  4. Drag and Drop sur une JTree
    Par Xhéras dans le forum Composants
    Réponses: 5
    Dernier message: 07/07/2006, 12h09
  5. Drag and drop sur un JTree
    Par tomca dans le forum Composants
    Réponses: 4
    Dernier message: 02/08/2005, 10h54

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