简体   繁体   中英

In JavaFX firing an event when the mouse is pressed and enters a node

In JavaFX, how can I fire an event when the mouse enters a node and the primary button is pressed? MOUSE_ENTERED doesn't work here as it doesn't fire an event when the mouse buttons are pressed. I am new in JavaFX and didn't find anything useful googling.

The MOUSE_ENTERED event is not triggered since a Click + Move counts as a drag. The MOUSE_DRAGGED event however is only triggered on the source of the drag. So the only way I can think of achieving this would be to listen to drag events on your scene, and filtering according to your criteria:

Button button = new Button("MyButton");
StackPane sp = new StackPane(button);
scene = new Scene(sp, 600, 600);
scene.setOnMouseDragged(ev -> {
    if (ev.getButton() != MouseButton.PRIMARY) return;
    if (ev.getPickResult().getIntersectedNode() != button && !button.getChildrenUnmodifiable().contains(ev.getPickResult().getIntersectedNode())) return;
    System.out.println("Hovered over the button while mouse button is pressed!");
});

The getPickResult().getIntersectedNode() returns the node which your drag intersects with right now. However depending on where you drag, this would not be the button but the text on the button. That's why I included the children as well.

Overall seems a bit hacky, but should do the trick.

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