Since the width
and height
properties are read-only you cannot bind them to anything, let alone each other. The reason they're read-only is documented:
Many of the Stage
properties are read only because they can be changed externally by the underlying platform and therefore must not be bindable [because bound properties cannot be set].
Both the width
and height
properties have similar statements in their documentation.
You can still add a listener to each property and, when one property changes, set the other property to the new value. To make sure this doesn't lead to a StackOverflowError
you'll have to track if you're currently setting the value in the listener. For example:
// not actually "binding" in the context of Property.bind(...)
public static void bindWidthAndHeightTogether(Window window, double widthToHeightRatio) {
ChangeListener<Number> listener =
new ChangeListener<>() {
private boolean changing;
@Override
public void changed(ObservableValue<? extends Number> obs, Number ov, Number nv) {
if (!changing) {
changing = true;
try {
if (obs == window.widthProperty()) {
window.setHeight(nv.doubleValue() / widthToHeightRatio);
} else {
window.setWidth(nv.doubleValue() * widthToHeightRatio);
}
} finally {
changing = false;
}
}
}
};
window.widthProperty().addListener(listener);
window.heightProperty().addListener(listener);
}
The above worked for me on Windows 10 using JavaFX 14. Note that it prevents the window from being maximized properly but not from going full-screen (at least on Windows 10).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…