How to make an undecorated window movable / draggable in JavaFX?

Shreyas Dave picture Shreyas Dave · Nov 3, 2012 · Viewed 17.9k times · Source

I have to create an application in which minimize and maximize button will be disabled.

I have used "StageStyle.UNDECORATED" with which the application will not be movable or draggable anymore, so I am searching for any other alternative to make my application.

Do anyone having solution for this?

Answer

pmoule picture pmoule · Nov 19, 2012

To achieve the window to be undecorated but still movable/dragable you have to handle the appropriate MouseEvent on any node of your choice.

Example:

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class SimpleWindowApplication extends Application {
    private double xOffset = 0;
    private double yOffset = 0;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.initStyle(StageStyle.UNDECORATED);
        BorderPane root = new BorderPane();

        root.setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                xOffset = event.getSceneX();
                yOffset = event.getSceneY();
            }
        });
        root.setOnMouseDragged(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                primaryStage.setX(event.getScreenX() - xOffset);
                primaryStage.setY(event.getScreenY() - yOffset);
            }
        });

        Scene scene = new Scene(root, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Learn more from the very valuable examples contained on Oracle's JavaFX download page under: JavaFX Demos and Samples