所以我在初始化时有这个:
double x = 1, y = 1;
while (x != 0 || y != 0) {
x = MouseInfo.getPointerInfo().getLocation().getX();
y = MouseInfo.getPointerInfo().getLocation().getY();
cursorXPositionLabel.setText("" + x);
cursorYPositionLabel.setText("" + y);
System.out.println("X = " + x + "\tY = " + y);
}
但是,直到光标不在(0,0)坐标上,应用程序才会启动。启用时,应用程序启动,标签显示0、0。我希望应用程序启动,并在移动光标的同时用实际坐标更新标签。
答案 0 :(得分:0)
对不起,我不明白您是否希望它扩展到应用程序之外,请查看此示例是否经过测试并可以正常工作
public class Main extends Application {
private Label xLabel;
private Label yLabel;
@Override
public void start(Stage primaryStage) {
xLabel = new Label("X Coordinate: 0");
yLabel = new Label("y Coordinate: 0");
VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
vBox.getChildren().addAll(xLabel, yLabel);
Scene scene = new Scene(vBox);
primaryStage.setScene(scene);
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.show();
updateCoordintates();
}
private void updateCoordintates(){
new Thread(()->{ //Splits off the Main thread
double lastX = 1;
double lastY = 1;
while (true) { //Will run forever you may want to change this not sure of your constraints
double x = MouseInfo.getPointerInfo().getLocation().getX();
double y = MouseInfo.getPointerInfo().getLocation().getY();
//The platform.runlater will allow you to post the change to the screen when available
if(x!=lastX)
Platform.runLater(()->xLabel.setText(String.valueOf(x)));
if(y!=lastY)
Platform.runLater(()->yLabel.setText(String.valueOf(y)));
lastX = x;
lastY = y;
System.out.println("X = " + x + "\tY = " + y);
}
}).start();
}
public static void main(String[] args) { launch(args); }
}
您不需要它在后台线程到这只是火̶.̶s̶e̶t̶O̶n̶M̶o̶u̶s̶e̶M̶o̶v̶e̶d̶
无论从任何容器您使用的下面是可运行的实施例的更新的坐标上移动