java fx控制鼠标,如何在JavaFX中获取鼠标的位置?
时间: 2024-02-03 10:11:31 浏览: 73
在JavaFX中,可以通过以下方式获取鼠标的位置:
1. 获取舞台对象
```java
Stage stage = (Stage) scene.getWindow();
```
2. 添加鼠标事件监听器
```java
scene.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
double mouseX = event.getX();
double mouseY = event.getY();
// do something with mouseX and mouseY
}
});
```
3. 在事件监听器中获取鼠标位置
```java
double mouseX = event.getX();
double mouseY = event.getY();
```
完整的示例代码如下:
```java
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class MousePositionDemo extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
scene.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
double mouseX = event.getX();
double mouseY = event.getY();
System.out.println("Mouse position: (" + mouseX + ", " + mouseY + ")");
}
});
}
public static void main(String[] args) {
launch(args);
}
}
```
阅读全文