简体   繁体   中英

How do I implement drag and drop on a canvas?

More specifically, how would I go about implementing a drag and drop feature so that the image file dragged on to the canvas would be drawn on the canvas? I've tried using a VBox listener on top of the canvas, but that didn't work. The source code of by program is available here .

In my controllers initialize() function, I have the following code. canvas is passed from the FXML file via the @FXML annotation:

public void initialize() {
        GraphicsContext g = canvas.getGraphicsContext2D();

        // Setter for brush type
        setBrushBrush();

        // Get screen dimensions and set the canvas accordingly
        Dimension screenSize = getScreenSize();
        double screenWidth = screenSize.getWidth();
        double screenHeight = screenSize.getHeight();
        canvas.setHeight(screenHeight/1.5);
        canvas.setWidth(screenWidth/1.5);

        canvas.setOnMouseDragged(e -> {
         //Drawing code here
        }); 

        canvas.setOnDragOver(e -> {
         // Need to read data of dragged image
        });

        canvas.setOnMouseDragReleased(e -> {
         // Need to put dragged data on to canvas
        });
}

The mouseDragReleased event is the wrong event to listen for here. That event is triggered when the mouse is released during a "full press-drag-release gesture" within the application; not when data is dropped during a "platform-supported drag-and-drop gesture" (see the documentation for MouseEvent for a description of these different dragging modes). So instead of canvas.setOnMouseDragReleased(...) , you need:

canvas.setOnDragDropped(e -> {
    // ...
});

Assuming the implementations of the handlers are correct, this should enable you to drop an image from a file and draw it on the canvas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM