简体   繁体   中英

Detecting Drag and Drop event on Java FX?

I got some Circle objects which I want to join with a Line when dragging from the circles.

I started with this code in order to test being and end drag and drop coordinates:

Circle nodo = new Circle(15.0);
nodo.setOnDragDetected(new EventHandler<MouseEvent>() {

    @Override
    public void handle(MouseEvent event) {
        coordenadas[0] = event.getX();
        coordenadas[1] = event.getY();
    }
});

nodo.setOnDragDropped(new EventHandler<DragEvent>() {

    @Override
    public void handle(DragEvent event) {
        coordenadas[2] = event.getX();
        coordenadas[3] = event.getY();
        System.out.println(coordenadas);
    }
});

When I try to drag a Circle nothing is being printed out to console when I drop the mouse. What's the correct approach and how should I being drawing a Line on dragging.

For detecting drag and drop, follow this approach:

        //
        // ON MOUSE PRESSED
        // ----------------------
        nodo.onMousePressedProperty().set(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                event.setDragDetect(true);
                nodo.setEffect(new DropShadow(10.0, Color.BLACK));
            }
        });

        //
        // ON MOUSE DRAGGED
        // ----------------------
        nodo.onMouseDraggedProperty().set(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                nodo.setEffect(new DropShadow(10.0, Color.BLUEVIOLET));

                /*
                final Circle indicator = new Circle(3);
                indicator.setStroke(Color.BLUEVIOLET);
                indicator.setCenterX(x);
                indicator.setCenterY(y);
                */

            }
        });

Change the commented part for whatever you need. In your case, save the initial event coordinates (X,Y) and, in the "dragged" part, use them as initial coordinates for your line.

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