Search code examples
javajavafxfxml

How to scale Nodes in jfxml without changing layoutX and layoutY


i am trying to re scale my pane to fit the resolution of the monitor. original window was made for a hd display.

for now i have tried using

     public void initialize(URL location, ResourceBundle resources) {
        Rectangle2D screenBounds = Screen.getPrimary().getBounds();
        double x = screenBounds.getWidth();
        double y = screenBounds.getHeight();
        double ratioX = x/1366;
        double ratioY = y/768;
        System.out.println(ratioX);
        System.out.println(ratioY);
        ObservableList<Node> l = pane.getChildren();
        for (Node n : l) {
            n.setScaleX(ratioX);
            n.setScaleY(ratioY);
            n.setLayoutX(n.getLayoutX() * ratioX);
            n.setLayoutY(n.getLayoutY() * ratioY);
        }

But the setScaleX and setScaleY expand the Node in a way that the Node does not originate in the given LayoutX an LayoutY. its expands to both left and right.

How can i scale the Node in a way that the top-left corner of the Node is always at the defined layoutX and layoutY


Solution

  • The pivot point of a node for the scale transformation applied using scaleX and scaleY is the center of the node. If you use a Scale transformation instead, you can specify the pivot point. As noted by @James_D in the comments it would probably be easier to apply the transformation to the parent btw.

    Scale scale = new Scale(
                        ratioX, ratioY,
                        0, 0 // pivot coordinates
                  );
    
    node.getTransforms().add(scale);
    

    Furthermore note that using different scale factors for both dimensions, the rendered result won't have the same ratio of height to width for your nodes.