我需要在我的應用程序中獲得鼠標點擊的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