我需要在我的应用程序中获得鼠标点击的x和y坐标。我在下面的代码中通过创建一个点来部分地解决它,但是根据我在屏幕上移动我的应用程序的窗口的位置,我得到不同的坐标。我会需要一些常量来确定某些对象。感谢您的帮助!JavaFX MousePosition
@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();
}
对于由James_D提供的代码,有一个错误:
将您的代码缩减到相关部分,然后澄清您的问题。这里有很多不相关的代码。 –
你的问题到底是什么?您已经获得了'MouseEvent'的X和Y坐标。 – eckig
这不是关于我的应用程序的窗口,而是整个屏幕。假设我在应用程序窗口中单击某个特定位置并记录(x,y),如果我在屏幕上移动我的应用程序窗口,再次单击相同的特定位置会生成不同的(x,y)。我希望它是一样的。 – Makaveli