Reputation: 197
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
});
}
Upvotes: 0
Views: 1212
Reputation: 209330
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.
Upvotes: 2