简体   繁体   English

javaFX鼠标事件过滤器

[英]javaFX mouse event filter

i trying to make a mouse event filter but its not working ,the consume() method is supposed to prevent the event from happenning and the label to stop showing the cursor location wheen exceed 200 units , but it keep showing it , any solution guys ? 我试图做一个鼠标事件过滤器,但是它不起作用,该consume()方法应该防止该事件的发生,并且标签停止显示光标位置超过200个单位时停止显示,但是它一直在显示它,有什么解决办法吗?

    package javafxapplication1;
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.input.KeyEvent;
    import javafx.scene.control.Label;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.FlowPane;
    import javafx.stage.Stage;

    /**
     *
     * @author Nadjib
     */
    public class nadjib extends Application {

         public static void main(String[] args) {
            Application.launch(args);
        }

        @Override
        public void start(Stage primaryStage) throws Exception {
            primaryStage.setTitle(" hello  ! ");
            FlowPane flowflow = new FlowPane();
            Scene scene = new Scene(flowflow,500,500);
            Label label = new Label("label man ");




           scene.addEventFilter(MouseEvent.MOUSE_MOVED,new 
          EventHandler<MouseEvent>(){ 

                @Override
                public void handle(MouseEvent event) {
                     label.setText("position x = : " + event.getScreenX() 
                 + " positoon y = " + event.getScreenY() );
                     if(event.getScreenX() > 200 ) event.consume();


                }
            });

            flowflow.getChildren().add(label);
            primaryStage.setScene(scene);
            primaryStage.show();
        }


    }

First of all, you're checking the value of screenX after updating the Label . 首先, 更新Label 之后 ,您要检查screenX的值。 So of course the Label will continue to update. 因此, Label当然会继续更新。

That being said, in the code you posted, there's no need to consume the event at all. 就是说,在您发布的代码中,根本不需要consume该事件。 Simply do nothing if the event.getScreenX() > 200 . 如果event.getScreenX() > 200则什么也不做。

The simplest way to do this is with a simple if/then block: 最简单的方法是使用简单的if/then块:

scene.addEventFilter(MouseEvent.MOUSE_MOVED, event -> {
    if (event.getScreenX() > 200) {
        return; // Do nothing
    } else {
        label.setText("position x = : " + event.getScreenX() + " positoon y = " + event.getScreenY());
    }
});

If this doesn't solve your issue, please edit your question and explain exactly what you're trying to accomplish. 如果这不能解决您的问题,请编辑您的问题,并确切说明您要完成的工作。 Right now, this will prevent the cursor locations from updating once X > 200 . 现在,这防止光标位置在X > 200更新。

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

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