javajavafxbluej

How do you detect when the cursor hovers over an object while the mouse is being pressed before the cursor enters the object?


The situation I'm currently in is, I have a circle on a screen and if I hold LMB down first and then drag my cursor across it, nothing happens. I've tried looking through different EventHandlers I could use, but I wasn't able to get them to work. Here is my code.

public class DragTester extends Application
{
    public static Group group = new Group();
    public static Scene scene = new Scene(group, 500, 500);
    @Override
    public void start(Stage stage)
    {
        for(int i = 0; i < 3; i++){
            DragBox DB = new DragBox(i * 150 + 100);
        }
        stage.setScene(scene);
        stage.show();
    }
}
public class DragBox
{
    private Circle c = new Circle(0, 0, 25);
    public DragBox(double x){
        DragTester.group.getChildren().add(c);
        c.setLayoutX(x);
        c.setLayoutY(250);
        c.setOnDragDetected(new EventHandler<MouseEvent>(){
            @Override public void handle(MouseEvent e){
                c.setFill(Color.rgb((int)(Math.random() * 255), (int)(Math.random() * 255), (int)(Math.random())));
            }
        });
    }
}

Solution

  • You can use the MOUSE_DRAG_ENTERED handler. This event is only fired during "full press-drag-release gestures", which you need to initiate on a DRAG_DETECTED event. See the Javadocs for more information.

    Here is your example, written to use this event. In this example, the "full press-drag-release gesture" is initiated on the scene:

    import java.util.Random;
    
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Circle;
    import javafx.stage.Stage;
    
    public class DragTester extends Application {
        private Group group = new Group();
        private Scene scene = new Scene(group, 500, 500);
        
        private Random rng = new Random();
    
        @Override
        public void start(Stage stage) {
            for (int i = 0; i < 3; i++) {
                DragBox DB = new DragBox(i * 150 + 100);
            }
            scene.setOnDragDetected(e -> scene.startFullDrag());
            stage.setScene(scene);
            stage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    
        class DragBox {
            private Circle c = new Circle(0, 0, 25);
    
            public DragBox(double x) {
                group.getChildren().add(c);
                c.setLayoutX(x);
                c.setLayoutY(250);
    
                c.setOnMouseDragEntered(e -> 
                    c.setFill(Color.rgb(rng.nextInt(256), rng.nextInt(256), rng.nextInt(256))));
            }
        }
    }