JavaFX MousePosition
I need to get the x and y coordinates of mouseclick in my application. I partially solved this in the code below by creating a point, but I keep getting different coordinates depending on where I move my application window on the screen. I would need something persistent to identify some obejcts later. Thanks for the help!
@Override
public void start(Stage stage) throws Exception {
final Pane root = new Pane();
setWidth(1400);
setHeight(1000);
Canvas background = new Canvas(getWidth(), getHeight());
final GraphicsContext context = background.getGraphicsContext2D();
File f = new File("background.png");
final Image image = new Image(new FileInputStream(f));
root.getChildren().add(background);
root.getChildren().add(b1);
b1.setLayoutX(1300);
b1.setLayoutY(10);
final Canvas animation = new Canvas(getWidth(), getHeight());
final Canvas animation2 = new Canvas(getWidth(), getHeight());
animation.setMouseTransparent(true);
animation2.setMouseTransparent(true);
final GraphicsContext context2 = animation.getGraphicsContext2D();
final GraphicsContext context3 = animation2.getGraphicsContext2D();
root.getChildren().add(animation);
root.getChildren().add(animation2);
Scene scene = new Scene(root, getWidth(), getHeight());
stage.setTitle("Old Gotham");
stage.setScene(scene);
stage.show();
final Duration oneFrameAmt = Duration.millis(1000 / 60);
final KeyFrame oneFrame;
oneFrame = new KeyFrame(oneFrameAmt,
new EventHandler() {
@Override
public void handle(Event event) {
context2.drawImage(image, 0, 0);
int offset = 700;
final Point p = MouseInfo.getPointerInfo().getLocation();
root.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
System.out.println(p.getX());
System.out.println(p.getY());
}
});
}
});
final Timeline tl = new Timeline(oneFrame);
tl.setCycleCount(Animation.INDEFINITE);
tl.play();
}
For the code provided by James_D, an error occurs:
source to share
I don't understand why you are setting a mouse listener inside the listener for the keyframe, but you need to get the coordinates from the mouse event.
MouseEvent
defines getX()
and getY()
to get the coordinates of the mouse event relative to the node itself, getSceneX()
and getSceneY()
to get the coordinates of the mouse event relative to everything Scene
and (in Java 8) getScreenX()
and getScreenY()
to get the coordinates of the mouse event relative to the screen coordinate system.
So, if you are interested in the location of the mouse relative to the window (scene), do
root.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println(event.getSceneX());
System.out.println(event.getSceneY());
}
});
source to share