简体   繁体   English

如何在画布上实现拖放?

[英]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. 我曾尝试在画布顶部使用VBox侦听器,但这没有用。 The source code of by program is available here . 按程序的源代码在此处

In my controllers initialize() function, I have the following code. 在我的控制器initialize()函数中,我有以下代码。 canvas is passed from the FXML file via the @FXML annotation: 通过@FXML批注从FXML文件传递canvas

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. mouseDragReleased事件是在此处监听的错误事件。 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). 而不是在“平台支持的拖放手势”期间删除数据时(有关这些不同的拖动模式的说明,请参见MouseEvent文档 )。 So instead of canvas.setOnMouseDragReleased(...) , you need: 因此,您需要:而不是canvas.setOnMouseDragReleased(...)

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. 假定处理程序的实现正确,这将使您能够从文件中删除图像并将其绘制在画布上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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