The pain with the pane in JavaFX. How can you scale Nodes with fixed Top-Left Corner?


Question

It seems to be a simple problem. But I found no simple solution. If you scale Nodes, the new form will be in the center of the parent. But I would like that the new form has the same Top-Left Corner as the old one.

The expample code is:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;


public class TestScale extends Application{
    Group root;
    Pane pane;
    Scene scene;    
    Rectangle rect0;

    @Override
    public void start(Stage stage) {
        root = new Group();
        scene = new Scene(root, 200, 160);
        rect0=new Rectangle(0, 0, 200, 160);
        rect0.setFill(Color.BLUE);
        pane = new Pane();           
        pane.getChildren().add(rect0);
        Button btnForward = new Button();
        btnForward.setText(">");
        btnForward.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                transform(pane);
            }
        });
        root.getChildren().add(pane);
        root.getChildren().add(btnForward);
        stage.setScene(scene);
        stage.show();

    }



    void transform (Node node){
        node.setScaleX(0.5);
        node.setScaleY(0.5);
    }

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

All tests with Stackpane, Borderpane, Anchorpane, Groups delivers no easy solution. The only way seems to be with setTransformX and setTransformY. But I need for this a complex calculation of the arguments.

1
2
6/24/2014 6:21:02 PM

When you use ScaleX/ScaleY, scaling occurs from the center of the node.

From JavaDocs

The pivot point about which the scale occurs is the center of the untransformed layoutBounds.

So, if you want to translate the scaling co-ordinates, you need to take the scaling compression into account when you set the required translation values.

As your current pivot is center, you need to set Translate to a negative value. Since the compression of X and Y is half, so you need to translate to 1/4 of total size of the scene.

node.setScaleX(0.5);
node.setScaleY(0.5);
node.setTranslateX(0 - node.getScene().getWidth()/4);     
node.setTranslateY(0 - node.getScene().getHeight()/4);
2
6/24/2014 7:35:25 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon