In the following example I bound a grey rectangle with a pane in height and width. The blue polygon should fit proportionally to the rectangle. This means that the borders of the rectangle and the polygon should have the same size, when I resize the window.
I guess I can achieve this with the .addListener method (via widthProperty and heightProperty) of the rectangle. But I did not succeed.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class PolygonFunktion extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Pane pane = new Pane();
//Rectangle
Rectangle rec = new Rectangle();
rec.setFill(Color.GRAY);
rec.layoutXProperty().set(20);
rec.layoutYProperty().set(20);
rec.widthProperty().bind(pane.widthProperty().subtract(rec.layoutXProperty().multiply(2)));
rec.heightProperty().bind(pane.heightProperty().subtract(rec.layoutYProperty().multiply(2)));
//Polygon
Polygon poly = new Polygon();
Double[] xy = {0.,0., 0.,-10., 10.,-10., 10.,-20., 20.,-20., 20.,-30., 30.,-30., 30.,0. };
poly.getPoints().addAll(xy);
poly.setFill(Color.BLUE);
poly.layoutXProperty().bind(rec.layoutXProperty());
poly.layoutYProperty().bind(rec.layoutYProperty().add(rec.heightProperty()));
rec.widthProperty().addListener( (o,oP,nP) -> {
//... ?
});
rec.heightProperty().addListener( (o,oP,nP) -> {
//... ?
});
pane.getChildren().add(rec);
pane.getChildren().add(poly);
stage.setScene(new Scene(pane, 300, 300));
stage.show();
}
}
I do not want to use scale methods, because the edge of the polygon would be scaled as well.
You can just update the points in the listener. Note that since each listener is doing the same thing, you only need one. Something like:
Instead of using bindings and listeners, however, it's probably better here to use a custom
Pane
and override thelayoutChildren()
method:This will ensure the calculations are only made once, each time the pane is laid out.