1 回答
TA贡献1796条经验 获得超4个赞
对不起,我不明白你希望它扩展到应用程序之外,检查出这个例子,它经过测试和工作
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); }
}
Y̶o̶u̶ ̶d̶o̶ ̶n̶o̶t̶ ̶n̶e̶e̶d̶ ̶t̶o̶ ̶i̶t̶ ̶o̶n̶ ̶a̶ ̶b̶a̶c̶k̶g̶r̶o̶u̶n̶d̶ ̶t̶h̶r̶e̶a̶d̶ ̶t̶o̶ ̶t̶h̶i̶s̶ ̶j̶u̶s̶t̶ ̶f̶i̶r̶e̶ ̶a̶ ̶ ̶f̶r̶o̶m̶ ̶w̶h̶a̶t̶e̶v̶e̶r̶ ̶c̶o̶n̶t̶a̶i̶n̶e̶r̶ ̶y̶o̶u̶ ̶a̶r̶e̶ ̶u̶s̶i̶n̶g̶ ̶h̶e̶r̶e̶ ̶i̶s̶ ̶a̶ ̶r̶u̶n̶n̶a̶b̶l̶e̶ ̶e̶x̶a̶m̶p̶l̶e̶ ̶t̶h̶a̶t̶ ̶u̶p̶d̶a̶t̶e̶s̶ ̶t̶h̶e̶ ̶c̶o̶o̶r̶d̶i̶n̶a̶t̶e̶s̶ ̶o̶n̶ ̶m̶o̶v̶e̶m̶e̶n̶t̶.̶s̶e̶t̶O̶n̶M̶o̶u̶s̶e̶M̶o̶v̶e̶d̶
添加回答
举报