Reputation: 21
I'm hoping someone can help me with a little problem. I am trying to track my mouse's location across the screen, which I've been able to do no problem. However, when it goes over a button, it stops tracking. Does anyone have any idea of how I might fix this? Here is a trivial example of the broader problem I'm trying to work on:
double x, y;
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage pStage) {
BorderPane bp = new BorderPane();
Scene scene = new Scene(bp, 500, 500);
pStage.setTitle("Show Circle");
pStage.setScene(scene);
pStage.show();
VBox centre = new VBox();
centre.setAlignment(Pos.CENTER);
centre.setPadding(new Insets(20, 20, 20, 20));
Button btn = new Button("hello");
centre.setPadding(new Insets(10, 10, 10, 10));
Label info = new Label("x: " + x + "\ny: " + y);
info.setPadding(new Insets(10, 10, 10, 10));
info.setFont(Font.font("Courier New", FontWeight.BOLD, 18));
centre.getChildren().addAll(info, btn);
bp.setCenter(centre);
x = 0;
y = 0;
scene.setOnMouseMoved(e -> {
x = e.getX();
y = e.getY();
info.setText("x: " + x + "\ny: " + y);
});
}
Thanks in advance!
Upvotes: 1
Views: 296
Reputation: 116
The application stops tracking the mouse event because the default (and expected) behaviour for controls is to consume all mouse events they receive. That is, these mouse events are prevented to be bubbling up (Event Delivery Process) to their parents. With this, the scene node (and all other parent nodes of the button) stops receiving mouse events whenever a mouse action is performed on the button.
Another solution would be to use an event filter because filters are called during the event capturing phase and thus before the JavaFX’s internal event handler consumes the mouse events for controls:
scene.addEventFilter(MouseEvent.MOUSE_MOVED, event -> {
x = event.getSceneX();
y = event.getSceneY();
info.setText("x: " + x + "\ny: " + y);
});
Upvotes: 0
Reputation: 360
Add new mouse move event for button also if you want to track the mouse cursor position over button also
btn.setOnMouseMoved(e -> {
x = e.getX();
y = e.getY();
info.setText("x: " + x + "\ny: " + y);
});
this will give you the coordinate in respect of the button. And if you want the position (coordinates) in respect of scene then use
x = e.getSceneX();
y = e.getSceneY();
Upvotes: -1
Reputation: 1544
Use mouse moved event handler and get x and y using event.getSceneX() and event.getSceneY() method like as:
btn.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent t) {
x = t.getSceneX();
y = t.getSceneY();
info.setText("x: " + x + "\ny: " + y);
}
});
Upvotes: 2