JavaFX如何定位鼠标

MrM*_*nik 5 mouse position javafx

我正在尝试做一些小游戏,在大多数游戏中,鼠标都被锁定在屏幕中央。因此,是否可以将鼠标锁定在屏幕中央或在JavaFX中设置鼠标的位置?我知道可以做到,而且我也知道一些用LWJGL或仅使用AWT / SWING包编写的示例。

感谢帮助。

GOX*_*LUS 6

2019 年 11 月 27 日更新

从现在开始,您还可以使用JavaFX 机器人 APIhttps : //openjfx.io/javadoc/11/javafx.graphics/javafx/scene/robot/Robot.html


这是您需要的代码:

import java.awt.AWTException;
import java.awt.Robot;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Screen;
import javafx.stage.Stage;

public class MoveCursor extends Application {

Scene scene;
VBox container;
Button moveMouse;
Button showHideCursor;
public static int screenWidth = (int) Screen.getPrimary().getBounds().getWidth();
public static int screenHeight = (int) Screen.getPrimary().getBounds().getHeight();

@Override
public void start(Stage stage) throws Exception {

    // MoveMouse Button
    moveMouse = new Button("Move Cursor to the center of Screen");
    moveMouse.setOnAction(m -> {
        moveCursor(screenWidth/2, screenHeight/2);
    });

    // ShowHide Cursor
    showHideCursor = new Button("Show/Hide Cursor");
    showHideCursor.setCursor(Cursor.HAND);
    showHideCursor.setOnAction(m -> {
        if (scene.getCursor() != Cursor.NONE)
            scene.setCursor(Cursor.NONE);
        else
            scene.setCursor(Cursor.DEFAULT);
    });

    // Container
    container = new VBox();
    container.getChildren().addAll(moveMouse, showHideCursor);

    // Scene
    scene = new Scene(container, 500, 500);

    stage.setScene(scene);
    stage.show();
}

/**
 * Move the mouse to the specific screen position
 * 
 * @param x
 * @param y
 */
public void moveCursor(int screenX, int screenY) {
    Platform.runLater(() -> {
        try {
            Robot robot = new Robot();
            robot.mouseMove(screenX, screenY);
        } catch (AWTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    });
}

public static void main(String[] args) {
    launch(args);
}

}
Run Code Online (Sandbox Code Playgroud)

  • @Slaw您还可以使用https://openjfx.io/javadoc/11/javafx.graphics/javafx/scene/robot/Robot.html (2认同)