I have made this interface:
public interface DraggedScene {
default void onDraggedScene(AnchorPane panelFather) {
AtomicReference<Double> xOffset = new AtomicReference<>((double) 0);
AtomicReference<Double> yOffset = new AtomicReference<>((double) 0);
panelFather.setOnMousePressed(e -> {
Stage stage = (Stage) panelFather.getScene().getWindow();
xOffset.set(stage.getX() - e.getScreenX());
yOffset.set(stage.getY() - e.getScreenY());
});
panelFather.setOnMouseDragged(e -> {
Stage stage = (Stage) panelFather.getScene().getWindow();
stage.setX(e.getScreenX() + xOffset.get());
stage.setY(e.getScreenY() + yOffset.get());
panelFather.setStyle("-fx-cursor: CLOSED_HAND;");
});
panelFather.setOnMouseReleased(e-> panelFather.setStyle("-fx-cursor: DEFAULT;"));
}
}
Note: The onDraggedScene method is called in the initialize method in each FXML controller after implementing the Initializable interface, this method is passed the parent panel in the fxml.
Example of its use:
public class ContainerController implements Initializable,DraggedScene {
@FXML
AnchorPane container;
@Override
public void initialize(URL location, ResourceBundle resources) {
this.onDraggedScene(this.container);
}
}