JavaFx--实现响应鼠标事件拖动窗体

public class DragWindowHandler implements EventHandler {

        private Stage primaryStage;        //primaryStage为start方法头中的Stage
        private double oldStageX;
        private double oldStageY;
        private double oldScreenX;
        private double oldScreenY;

        public DragWindowHandler(Stage primaryStage) {        //构造器
            this.primaryStage = primaryStage;
        }

        @Override
        public void handle(MouseEvent e) {
            if (e.getEventType() == MouseEvent.MOUSE_PRESSED) {    //鼠标按下的事件    
                this.oldStageX = this.primaryStage.getX();
                this.oldStageY = this.primaryStage.getY();
                this.oldScreenX = e.getScreenX();
                this.oldScreenY = e.getScreenY();

            } else if (e.getEventType() == MouseEvent.MOUSE_DRAGGED) {  //鼠标拖动的事件
                this.primaryStage.setX(e.getScreenX() - this.oldScreenX + this.oldStageX);
                this.primaryStage.setY(e.getScreenY() - this.oldScreenY + this.oldStageY);
            }
        }
    }
EventHandler handler = new DragWindowHandler(this.primaryStage);        //primaryStage为start方法中的局部b
this.setOnMousePressed(handler);    //如果去掉这一行代码将会使鼠标进入面板时面板左上角会定位到鼠标的位置
this.setOnMouseDragged(handler);


你可能感兴趣的:(Java相关)