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

JavaFX Discussion :

[javafx] Drag and Drop dans un treeview


Sujet :

JavaFX

  1. #1
    bul
    bul est déconnecté
    Membre confirmé Avatar de bul
    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    195
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2003
    Messages : 195
    Par défaut [javafx] Drag and Drop dans un treeview
    bonjour à tous,

    comment déplacer "b1" vers "a" (par exemple) dans un treeview
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    -a
    --a1
    --a2
    -b
    --b1
    --b2
    -c
    --c1
    --C2
    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
     
    tree.setOnDragDetected...
    tree.setOnDragOver...
    tree.setOnDragDropped ( new EventHandler<DragEvent>() {
     @Override public void handle(DragEvent event) {
      Dragboard db=event.getDragboard();
      boolean success=false;
      if ( event.getDragboard().hasString() ) {
       System.out.println("déplacer "+db.getString());
       success=true;
      }
      event.setDropCompleted(success);
      event.consume();
     }
    });
    je "sais" récupérer "b1" ( db.getString() ), mais
    comment savoir que le curseur pointe sur "a", ou
    "a1", ou "a2"... au moment de "dropper" ?

    merci d'avance.

  2. #2
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 897
    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 897
    Billets dans le blog
    54
    Par défaut
    Donc la réponse que tu as eut sur OTN est que la logique du DnD doit être implementee au niveau du TreeCell plutôt que du TreeView lui-même.

    Voici une implémentation très très basique mais fonctionnelle :
    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
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package test;
     
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.TreeCell;
    import javafx.scene.control.TreeItem;
    import javafx.scene.control.TreeView;
    import javafx.scene.control.TreeViewBuilder;
    import javafx.scene.input.ClipboardContent;
    import javafx.scene.input.DataFormat;
    import javafx.scene.input.DragEvent;
    import javafx.scene.input.Dragboard;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.input.TransferMode;
    import javafx.scene.layout.AnchorPane;
    import javafx.scene.layout.AnchorPaneBuilder;
    import javafx.stage.Stage;
    import javafx.util.Callback;
     
    /**
     *
     * @author fabriceb
     */
    public class Main extends Application {
     
        /**
         *
         * @author fabriceb
         */
        public class DnDCell extends TreeCell<Integer> {
     
            private TreeView<Integer> parentTree;
     
            public DnDCell(final TreeView<Integer> parentTree) {
                this.parentTree = parentTree;
                // ON SOURCE NODE.
                setOnDragDetected(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        System.out.println("Drag detected on " + item);
                        if (item == null) {
                            return;
                        }
                        Dragboard dragBoard = startDragAndDrop(TransferMode.MOVE);
                        ClipboardContent content = new ClipboardContent();
                        content.put(DataFormat.PLAIN_TEXT, item.toString());
                        dragBoard.setContent(content);
                        event.consume();
                    }
                });
                setOnDragDone(new EventHandler<DragEvent>() {
                    @Override
                    public void handle(DragEvent dragEvent) {
                        System.out.println("Drag done on " + item);
                        dragEvent.consume();
                    }
                });
                // ON TARGET NODE.
    //            setOnDragEntered(new EventHandler<DragEvent>() {
    //                @Override
    //                public void handle(DragEvent dragEvent) {
    //                    System.out.println("Drag entered on " + item);
    //                    dragEvent.consume();
    //                }
    //            });        
                setOnDragOver(new EventHandler<DragEvent>() {
                    @Override
                    public void handle(DragEvent dragEvent) {
                        System.out.println("Drag over on " + item);
                        if (dragEvent.getDragboard().hasString()) {
                            int valueToMove = Integer.parseInt(dragEvent.getDragboard().getString());
                            if (valueToMove != item) {
                                // We accept the transfert !!!!!
                                dragEvent.acceptTransferModes(TransferMode.MOVE);
                            }
                        }
                        dragEvent.consume();
                    }
                });
    //            setOnDragExited(new EventHandler<DragEvent>() {
    //                @Override
    //                public void handle(DragEvent dragEvent) {
    //                    System.out.println("Drag exited on " + item);
    //                    dragEvent.consume();
    //                }
    //            });        
                setOnDragDropped(new EventHandler<DragEvent>() {
                    @Override
                    public void handle(DragEvent dragEvent) {
                        System.out.println("Drag dropped on " + item);
                        int valueToMove = Integer.parseInt(dragEvent.getDragboard().getString());
                        TreeItem<Integer> itemToMove = search(parentTree.getRoot(), valueToMove);
                        TreeItem<Integer> newParent = search(parentTree.getRoot(), item);
                        // Remove from former parent.
                        itemToMove.getParent().getChildren().remove(itemToMove);
                        // Add to new parent.
                        newParent.getChildren().add(itemToMove);
                        newParent.setExpanded(true);
                        dragEvent.consume();
                    }
                });
            }
     
            private TreeItem<Integer> search(final TreeItem<Integer> currentNode, final int valueToSearch) {
                TreeItem<Integer> result = null;
                if (currentNode.getValue() == valueToSearch) {
                    result = currentNode;
                } else if (!currentNode.isLeaf()) {
                    for (TreeItem<Integer> child : currentNode.getChildren()) {
                        result = search(child, valueToSearch);
                        if (result != null) {
                            break;
                        }
                    }
                }
                return result;
            }
            private Integer item;
     
            @Override
            protected void updateItem(Integer item, boolean empty) {
                super.updateItem(item, empty);
                this.item = item;
                String text = (item == null) ? null : item.toString();
                setText(text);
            }
        }
     
        @Override
        public void start(Stage primaryStage) {
            TreeItem<Integer> treeRoot = new TreeItem(0);
            treeRoot.getChildren().add(new TreeItem(1));
            treeRoot.getChildren().add(new TreeItem(2));
            treeRoot.getChildren().add(new TreeItem(3));
            TreeView<Integer> treeView = TreeViewBuilder.<Integer>create().root(treeRoot).build();
            treeView.setCellFactory(new Callback<TreeView<Integer>, TreeCell<Integer>>() {
                @Override
                public TreeCell call(TreeView<Integer> param) {
                    return new DnDCell(param);
                }
            });
            AnchorPane.setTopAnchor(treeView, 0d);
            AnchorPane.setRightAnchor(treeView, 0d);
            AnchorPane.setBottomAnchor(treeView, 0d);
            AnchorPane.setLeftAnchor(treeView, 0d);
            //
            AnchorPane root = AnchorPaneBuilder.create().children(treeView).build();
            Scene scene = new Scene(root, 300, 250);
            //
            primaryStage.setTitle("Hello World!");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
     
        /**
         * The main() method is ignored in correctly deployed JavaFX 
         * application. main() serves only as fallback in case the 
         * application can not be launched through deployment artifacts,
         * e.g., in IDEs with limited FX support. NetBeans ignores main().
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            launch(args);
        }
    }
    Cependant d'autres tests doivent être implémentés pour éviter des bugs et crash en tout genre :
    - prendre en compte qu'on ne devrait pas pouvoir déplacer le noeud racine.
    - et de manière générale : un noeud cible ne devraient pas pouvoir accepter la réception d'un noeud source qui est un de ses ancêtres.

    Mais ca je te laisse le soin de gerer ca toi-même

    Et bon, mon test est fait avec de simple entiers, il faudra faire un peu plus de modifications pour faire transiter d'autre types d'objets (je ne me suis pas trop penche sur le DnD de JavaFX mais celui de Swing permettait de placer des objets de la JVM dans le buffer de transfert).
    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

  3. #3
    bul
    bul est déconnecté
    Membre confirmé Avatar de bul
    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    195
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2003
    Messages : 195
    Par défaut
    merci de la réponse et de l'exemple complet.
    je n'avais rien compris sur l'autre site,
    conscient bien sur des tests à ajouter
    @+

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

Discussions similaires

  1. Destination du drag and drop dans treeview
    Par chrisdot dans le forum Silverlight
    Réponses: 1
    Dernier message: 13/01/2011, 17h11
  2. [VB.net] Drag and drop dans une Treeview
    Par gégécap dans le forum Windows Forms
    Réponses: 2
    Dernier message: 19/10/2006, 10h05
  3. [VB.NET]Drag and Drop dans une Listview
    Par gégécap dans le forum Windows Forms
    Réponses: 5
    Dernier message: 23/08/2006, 18h41
  4. [Débutant(e)][VB.NET] Drag and drop entre 2 treeviews
    Par - Manuella Leray - dans le forum Windows Forms
    Réponses: 8
    Dernier message: 13/10/2005, 15h54
  5. Drag and drop dans un TTreeView
    Par BigBenQ dans le forum C++Builder
    Réponses: 3
    Dernier message: 07/10/2005, 14h57

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