JavaFX的窗体为“StageStyle.UNDECORATED”时,如何使用鼠标移动窗体

Posted vwvwvwgwg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaFX的窗体为“StageStyle.UNDECORATED”时,如何使用鼠标移动窗体相关的知识,希望对你有一定的参考价值。

如题,因为“StageStyle.UNDECORATED”将会title bar隐藏,用户无法使用鼠标移动窗体。需要通过增加鼠标的“Pressed”、“Dragged”事件处理获取鼠标信息来移动窗体。具体代码如下。

/**
 * @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) {
        launch(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 mouse pressed and dragged even handlers for the scene
        scene.setOnMousePressed(e -> handleMousePressed(e));
        scene.setOnMouseDragged(e -> handleMouseDragged(e));
        
        stage.setScene(scene);
        stage.setTitle("Moving a Stage");
        stage.initStyle(StageStyle.UNDECORATED);
        stage.show();
    }

    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;
    private double dragOffsetX;
    private double dragOffsetY;
}

 

以上是关于JavaFX的窗体为“StageStyle.UNDECORATED”时,如何使用鼠标移动窗体的主要内容,如果未能解决你的问题,请参考以下文章

javafx窗体面板位置

JavaFx:打开另外一个窗体并加载WebView

javaFX的窗体----css+java

javafx 如何设置窗体图标,就是左上角的咖啡图标,怎么替换掉?

javafx2 用一个按钮 怎么关闭当前 窗体 类似红叉功能

javafx编程问题