JavaFX学习 EventFilter

   EventFilter可以让你在事件捕捉过程中处理一些东西
public void init(Group root){
		HBox box = new HBox();
		box.setStyle("-fx-background-color:#EEEEEE");
		box.setPrefSize(300, 300);
		box.setOnMousePressed(new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent arg0) {
				System.out.println("box mouse pressed");
			}
			
		});
		box.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent arg0) {
				System.out.println("box filter");
				//arg0.consume();
			}
			
		});
		Button button = new Button("Click");
		button.setOnMousePressed(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent arg0) {
				System.out.println("button mouse pressed");
			}
			
		});
		button.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent arg0) {
				System.out.println("button filter");
			}
			
		});
		box.getChildren().add(button);
		Rectangle rect = new Rectangle();
		rect.setHeight(200);
		rect.setWidth(200);
		rect.setFill(Color.RED);
		
		rect.setOnMousePressed(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent arg0) {
				System.out.println("rect mouse pressed");
			}
			
		});
		rect.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent arg0) {
				System.out.println("rect filter");
			}
			
		});
		box.getChildren().add(rect);
		root.setOnMousePressed(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent arg0) {
				System.out.println("root mouse pressed");
			}
			
		});
		root.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent arg0) {
				System.out.println("root filter");
				//arg0.consume();
			}
			
		});
		root.getChildren().add(box);
	}

当你点击rectangle的时候,输出:
root filter
box filter
rect filter
rect mouse pressed
box mouse pressed
root mouse pressed
这里可以看到执行的顺序...- root filter- box filter- rect filter - rect Event - box event - root event...
当我点击button时,输出
root filter
box filter
button filter
button mouse pressed
与rectangle不同button event执行后,root event没有执行了,我猜测可能是button event中添加了event.consume()把事件给使用了,从而后面不会传递下去。
当我在rect event添加了event.consume()此时,执行效果和button一样。

从上面例子可以得到,事件的传递执行过程stage filter- scene filter-root filter-subRoot -...-subRoot event- root event-scene event - stage event。
filter执行在event的传递过程中,所以我们可以在event执行前,做我们所需要的操作。

你可能感兴趣的:(事件,event,JavaFX,eventfilter)