【问题标题】:How do you detect when the cursor hovers over an object while the mouse is being pressed before the cursor enters the object?在光标进入对象之前按下鼠标时,如何检测光标何时悬停在对象上?
【发布时间】:2021-12-17 05:24:54
【问题描述】:

我目前的情况是,我在屏幕上有一个圆圈,如果我先按住 LMB 然后将光标拖过它,什么也不会发生。我已经尝试过查看我可以使用的不同 EventHandler,但我无法让它们工作。这是我的代码。

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())));
            }
        });
    }
}

【问题讨论】:

    标签: java javafx bluej


    【解决方案1】:

    您可以使用MOUSE_DRAG_ENTERED 处理程序。此事件仅在“完全按下-拖动-释放手势”期间触发,您需要在 DRAG_DETECTED 事件上启动该事件。请参阅Javadocs 了解更多信息。

    这是您的示例,是为使用此事件而编写的。在这个例子中,“完全按下-拖动-释放手势”是在场景中启动的:

    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))));
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 2020-11-13
      • 2014-02-25
      相关资源
      最近更新 更多