while循环导致窗口在JavaFX中崩溃

0 java javafx

我正在尝试创建一个非常简单易用的程序,主动读取和显示鼠标的位置.我已经看过很多教程,只有当它在GUI应用程序的窗口内时,或者在按下按钮后才能创建读取鼠标位置的程序,但我想要一个在屏幕的所有区域显示鼠标位置的程序.这就是我所拥有的:

import java.awt.MouseInfo;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class MouseCoordinates extends Application{

     public static void main(String[] args) {

          launch();

     }

     public void start(Stage primaryStage) throws Exception{
          primaryStage.setTitle("Mouse Reader");
          Label x = new Label();
          Label y = new Label();
          StackPane layout = new StackPane();
          layout.getChildren().addAll(x, y);

          Scene scene = new Scene(layout, 600, 500);
          primaryStage.setScene(scene);
          primaryStage.show ();

          double mouseX = 1.0;
          double mouseY = 1.0;

          while(true){
               mouseX = MouseInfo.getPointerInfo().getLocation().getX();
               mouseY = MouseInfo.getPointerInfo().getLocation().getY();
               x.setText("" + mouseX);
               y.setText("" + mouseY);
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

我知道这个while循环是窗口崩溃的原因,但我无法找到解决方法.任何人都可以解释为什么我不能使用JavaFX的while循环,以及解决这个问题的方法?

dav*_*xxx 5

您的start()方法没有任何更改退出循环,因此在您定义无限循环时返回:while(true){...}不带return语句.

为什么不用Timeline

Timeline timeLine = new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {

    @Override
    public void handle(ActionEvent event) {
        mouseX = MouseInfo.getPointerInfo().getLocation().getX();
        mouseY = MouseInfo.getPointerInfo().getLocation().getY();
        x.setText("" + mouseX);
        y.setText("" + mouseY);
    }
}));
timeLine.setCycleCount(Timeline.INDEFINITE);
timeLine.play();
Run Code Online (Sandbox Code Playgroud)

或者用lambda:

Timeline timeLine = new Timeline(new KeyFrame(Duration.seconds(1), 
    e -> {
           mouseX = MouseInfo.getPointerInfo().getLocation().getX();
           mouseY = MouseInfo.getPointerInfo().getLocation().getY();
           x.setText("" + mouseX);
           y.setText("" + mouseY);
         }   
));
timeLine.setCycleCount(Timeline.INDEFINITE);
timeLine.play();
Run Code Online (Sandbox Code Playgroud)

解决您的要求的另一种方式,可以使用addEventFilter( MouseEvent.MOUSE_MOVED)在上StackPane对象:

layout.addEventFilter(MouseEvent.MOUSE_MOVED, e -> {             
       x.setText("" + e.getScreenX());
       y.setText("" + e.getScreenY());
});
Run Code Online (Sandbox Code Playgroud)

MouseEvent类提供装置上,并且所述源组件上X和Y两者的绝对位置:

getScreenX()
Run Code Online (Sandbox Code Playgroud)

返回事件的绝对水平位置.

getScreenY()
Run Code Online (Sandbox Code Playgroud)

返回事件的绝对垂直y位置

getX();
Run Code Online (Sandbox Code Playgroud)

事件相对于MouseEvent源的原点的水平位置.

getY();
Run Code Online (Sandbox Code Playgroud)

事件相对于MouseEvent源的原点的垂直位置.