I am having an issue with scaling a group containing shapes, and dragging the shapes around.
In the example below, I have a group containing 2 rectangles, after scaling the group, if I drag one of the rectangles, the other will go negative the distance of the other, i.e., if I drag the rectangle r2 down, the rectangle r will go up, etc
I am wondering if this is some sort of bug, or what the issue is here?
The code below is a working example of what my issue is.
NOTE: I ran a test on the bounds, and it only changes when the dragged rectangle moves outside the current bounds.
if moving to the bottom right the new bounds will be something similar to
BoundingBox [minX:250.0, minY:250.0, minZ:0.0, width:301.7606201171875, height:338.6553955078125, depth:0.0, maxX:551.7606201171875, maxY:588.6553955078125, maxZ:0.0]
Even though the other rectangle moves outside of the minX
and minY
bounds.
import javafx.scene.shape.Rectangle;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SampleScale extends Application {
@Override
public void start(Stage primaryStage) {
Group g = new Group();
Rectangle r = new Rectangle(250,250,10,10);
Rectangle r2 = new Rectangle(260,260,10,10);
r2.setFill(Color.RED);
r2.setOnMouseDragged(event
->
{
r2.setTranslateX(r2.getTranslateX() + (event.getX() -r2.getX()));
r2.setTranslateY(r2.getTranslateY() + (event.getY() -r2.getY()));
g.autosize();
event.consume();
});
Pane p = new Pane();
p.setPrefSize(1000, 1000);
g.getChildren().addAll(r,r2);
p.getChildren().addAll(g);// comment out to test bottom code;
//default works
//g.setScaleX(1);
//g.setScaleY(1);
//causes other node to move negative distance of the other object
// i.e., if r2 is dragged down, r will move up, etc.
g.setScaleX(2);
g.setScaleY(2);
//-------------------------
//this works if not placed inside a group
// p.getChildren().addAll(r,r2);
// r.setScaleX(2);
// r.setScaleY(2);
// r2.setScaleX(2);
// r2.setScaleY(2);
Scene scene = new Scene(p, 1300, 1250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
The scaleX
and scaleY
properties use the center of a node as pivot point for scaling. Since moving r2
resizes the Group
, the other children also move.
You could apply a Scale
transform with pivot point (0, 0)
instead:
// g.setScaleX(2);
// g.setScaleY(2);
g.getTransforms().add(new Scale(2, 2, 0, 0));