Issue
While this stackoverflow post helps solve the drag issue How to drag an undecorated window (stage) of JavaFX
It definitly doesn't let window snap work, is there some way i'm supposed to use this to get window snap working?
Solution
This is a single Class javafx App you can try . You can drag the stage with the green circle and close App with the red one . when stage.getX==0
is at the left of the screen and the app resize at maxHeight
of the screen wich is in Screen.getPrimary().getBounds().getMaxY()
and Screen.getPrimary().getBounds().getMaxX()
divided by two to get half width of the screen . for the right side is a litte bit tricky when stage.getX()
pluss the current width of the window matchs Screen.getPrimary().getBounds().getMaxY()
means the right side of the window reaches the right side of the screen , but when the app is rezised in the right its x coordinate change , that will trigger the listener again , to avoid that I put a boolean boolean isInRightSide
. You can comment and uncomment that boolean to see that behavior . Any other values of x position of the stage will reset to the original sizes .
public class App extends Application {
boolean isInRightSide = false;
double offsetX;
double offsetY;
int defaultWidth = 640;
int defaultHeight = 480;
@Override
public void start(Stage stage) {
double screenMaxX = Screen.getPrimary().getBounds().getWidth();
System.out.println(Screen.getPrimary().getBounds());
Circle dragCircle = new Circle(30, new Color(0, 1, 0, 1));
Circle closeCircle = new Circle(30, new Color(1, 0, 0, 1));
HBox hBox = new HBox(dragCircle, closeCircle);
closeCircle.setOnMouseClicked(e -> stage.close());
hBox.setAlignment(Pos.TOP_RIGHT);
dragCircle.setOnMousePressed(e -> {
offsetX = e.getSceneX();
offsetY = e.getSceneY();
}
);
dragCircle.setOnMouseDragged(e -> {
stage.setX(e.getScreenX() - offsetX);
stage.setY(e.getScreenY() - offsetY);
e.consume();
});
// sanap to left and right
stage.xProperty().addListener(e -> {
if (stage.getX() + defaultWidth > screenMaxX) {
stage.setX(screenMaxX - defaultWidth);
}
if (stage.getX() <= 0 && !stage.isFullScreen()) {
stage.setHeight(Screen.getPrimary().getBounds().getMaxY());
stage.setWidth(Screen.getPrimary().getBounds().getMaxX() / 2);
} else if (!isInRightSide) {
stage.setHeight(defaultHeight);
stage.setWidth(defaultWidth);
}
if (stage.getX() + defaultWidth == screenMaxX) {
isInRightSide = true;
stage.setHeight(Screen.getPrimary().getBounds().getMaxY());
stage.setWidth(Screen.getPrimary().getBounds().getMaxX() / 2);
} else {
isInRightSide = false;
}
});
stage.initStyle(StageStyle.UNDECORATED);
Scene scene = new Scene(new AnchorPane(hBox), defaultWidth, defaultHeight);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
app snap when reaches right side
Answered By - Giovanni Contreras
Answer Checked By - Timothy Miller (JavaFixing Admin)