拖动StageStyle.UNDECORATED的窗体

北慕城南 提交于 2020-08-11 00:56:57

在JavaFX中,可以通过在窗体的边框上点击鼠标(不松开)进行拖动,但是当窗体设置为“StageStyle.UNDECORATED”,没有边框,或者在窗体的scene中拖动窗体该如何操作呢?

可以供过在窗体中对scene的“setOnMousePressed”和“setOnMouseDragged”事件重写,处理鼠标事件,拖动窗体。具体示例代码如下:

package ch04;

/**
 * @package ch04
 * @date 2020/5/5
 * @author qiaowei
 * @version 1.0
 * @description
 */

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class DraggingStage extends Application {

    public static void main(String[] args) {
        Application.launch(DraggingStage.class, args);
    }

    @Override
    public void start(Stage primaryStage) {
        // Store the stage reference in the instance variable to
        // use it in the mouse pressed event handler later.
        this.stage = primaryStage;
        
        Label msgLabel = new Label("Press the mouse button and drag.");
        
        Button closeButton = new Button("Close");
//        closeButton.setOnAction(e -> stage.close());
        closeButton.setOnAction(e -> primaryStage.close());
        
        VBox root = new VBox();
        root.getChildren().addAll(msgLabel, closeButton);
        
        Scene scene = new Scene(root, 300, 200);
        // Set lambda of mouse pressed and dragged even handlers for the scene
        scene.setOnMousePressed((ev) -> handleMousePressed(ev));
//        scene.setOnMousePressed(this::handleMousePressed(e));
        scene.setOnMouseDragged(e -> handleMouseDragged(e));
        
        stage.setScene(scene);
        stage.setTitle("Moving a Stage");
        stage.initStyle(StageStyle.UNDECORATED);
        stage.show();
    }

    /**
      @class      DraggingStage
      @date       2020/5/24
      @author     qiaowei
      @version    1.0
      @brief      点击鼠标时触发事件
      @param      e 鼠标事件
     */
    protected void handleMousePressed(MouseEvent e) {
        // Store the mouse x and y coordinates with respect to the
        // stage in the reference variables to use them in the drag event
        // 点击鼠标时,获取鼠标在窗体上点击时相对应窗体左上角的偏移
        this.dragOffsetX = e.getScreenX() - stage.getX();
        this.dragOffsetY = e.getScreenY() - stage.getY();
    }
    
    protected void handleMouseDragged(MouseEvent e) {
        // Move the stage by the drag amount
        // 拖动鼠标后,获取鼠标相对应显示器坐标减去鼠标相对窗体的坐标,并将其设置为窗体在显示器上的坐标
        stage.setX(e.getScreenX() - this.dragOffsetX);
        stage.setY(e.getScreenY() - this.dragOffsetY);
    }

    private Stage stage;
    
    // 点击鼠标时的x坐标值
    private double dragOffsetX;
    
    // 点击鼠标时的y坐标值
    private double dragOffsetY;
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!