Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

java - Drag and Drop from ListView to TreeView

I just want to drag and drop an item from my ListView to a specific position in my TreeView. I know how to handle DragEvents. But how can I get the dropped position of my treeView? With "position" I mean "on which treeview-item dropped (get reference from this treeview-item)".

package main;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;



public class Program extends Application {
    String buffer = "";

    public static void main(String args[]) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Tree View Sample");
        HBox box = new HBox();

        //ListView
        ListView<String> list = new ListView<String>();
        ObservableList<String> items = FXCollections.observableArrayList(
                "Single", "Double", "Suite", "Family App");
        list.setItems(items);
        list.setOnDragDetected(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                System.out.println("Drag something from ListView");
            }
        });
        //TreeView
        TreeItem<String> rootItem = new TreeItem<String>("Inbox");
        rootItem.setExpanded(true);
        for (int i = 1; i < 6; i++) {
            TreeItem<String> item = new TreeItem<String>("Message" + i);
            rootItem.getChildren().add(item);
        }
        TreeView<String> treeView = new TreeView<String>(rootItem);
        treeView.setEditable(true);
        treeView.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
            @Override
            public TreeCell<String> call(TreeView<String> stringTreeView) {
                TreeCell<String> treeCell = new TreeCell<String>() {
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item);
                        }
                    }
                };

                treeCell.setOnDragDetected(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent mouseEvent) {
                        System.out.println("Drag: " + treeCell.getItem());
                    }
                });

                treeCell.setOnDragDropped(new EventHandler<DragEvent>() {
                    public void handle(DragEvent event) {
                        //THIS METHOD DOESN'T WORK (It doesn't called, when i drag something from listview to treeview)
                        System.out.println("Dropped something");
                        event.setDropCompleted(true);
                        event.consume();
                    }
                });

                return treeCell;
            }
        });

        box.getChildren().addAll(list,treeView);
        //Create Scene
        Scene scene = new Scene(box);

        //Add Scene to Stage..
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Nothing is working except the setOnDragDetected handler. Why?
Example what I'm trying:
Want to change via drag and drop Message 2 with "Double".
Or I want to change Message 1 with "Single".
The code above is just a test for a larger project.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to

  • startDragAndDrop() on DRAG_DETECTED source event
  • acceptTransferModes() on DRAG_OVER target event
  • and event.getDragboard().getString() on DRAG_DROPPED target event

See this full example:

@Override
public void start( Stage primaryStage ) throws Exception
{
    HBox box = new HBox();

    // ListView
    ListView<String> list = new ListView<String>( FXCollections.observableArrayList( "Single", "Double", "Suite", "Family App" ) );

    list.setCellFactory( new Callback<ListView<String>, ListCell<String>>()
    {
        @Override
        public ListCell<String> call( ListView<String> param )
        {
            ListCell<String> listCell = new ListCell<String>()
            {
                @Override
                protected void updateItem( String item, boolean empty )
                {
                    super.updateItem( item, empty );
                    setText( item );
                }
            };

            listCell.setOnDragDetected( ( MouseEvent event ) ->
            {
                System.out.println( "listcell setOnDragDetected" );
                Dragboard db = listCell.startDragAndDrop( TransferMode.COPY );
                ClipboardContent content = new ClipboardContent();
                content.putString( listCell.getItem() );
                db.setContent( content );
                event.consume();
            } );

            return listCell;
        }
    } );

    //TreeView
    TreeItem<String> rootItem = new TreeItem<>( "Inbox" );
    rootItem.setExpanded( true );
    for ( int i = 1; i < 6; i++ )
    {
        TreeItem<String> item = new TreeItem<>( "Message " + i );
        rootItem.getChildren().add( item );
    }
    TreeView<String> treeView = new TreeView<>( rootItem );
    treeView.setEditable( true );

    treeView.setCellFactory( new Callback<TreeView<String>, TreeCell<String>>()
    {
        @Override
        public TreeCell<String> call( TreeView<String> stringTreeView )
        {
            TreeCell<String> treeCell = new TreeCell<String>()
            {
                @Override
                protected void updateItem( String item, boolean empty )
                {
                    super.updateItem( item, empty );
                    if ( item != null )
                    {
                        setText( item );
                    }
                }
            };

            treeCell.setOnDragEntered( ( DragEvent event ) ->
            {
                treeCell.setStyle( "-fx-background-color: aqua;" );
            } );

            treeCell.setOnDragExited( ( DragEvent event ) ->
            {
                treeCell.setStyle( "" );
            } );

            treeCell.setOnDragOver( ( DragEvent event ) ->
            {
                Dragboard db = event.getDragboard();
                if ( db.hasString() )
                {
                    event.acceptTransferModes( TransferMode.COPY_OR_MOVE );
                }
                event.consume();
            } );

            treeCell.setOnDragDropped( ( DragEvent event ) ->
            {
                System.out.println( "treeCell.setOnDragDropped" );
                Dragboard db = event.getDragboard();
                boolean success = false;
                if ( db.hasString() )
                {
                    System.out.println( "Dropped: " + db.getString() );
                    treeCell.getTreeItem().getChildren().add( new TreeItem<>( db.getString() ) );
                    treeCell.getTreeItem().setExpanded( true );
                    success = true;
                }
                event.setDropCompleted( success );
                event.consume();
            } );

            return treeCell;
        }
    } );

    box.getChildren().addAll( list, treeView );
    primaryStage.setScene( new Scene( box ) );
    primaryStage.show();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...