Skip to content

Instantly share code, notes, and snippets.

@james-d
Last active August 14, 2023 15:47
Show Gist options
  • Save james-d/08971a9d511727ea44d72917dec40e20 to your computer and use it in GitHub Desktop.
Save james-d/08971a9d511727ea44d72917dec40e20 to your computer and use it in GitHub Desktop.
Demo of why it is bad to use bindings to make a responsive image container. Here adding padding to the container holding the image (which can be done with an external stylesheet) causes the image to grow indefinitely.
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class BindingImageSizeDemo extends Application {
private Node createImageHolder(ImageView imageView) {
BorderPane container = new BorderPane(imageView);
// BROKEN. DO NOT USE THIS APPROACH:
imageView.fitWidthProperty().bind(container.widthProperty());
imageView.fitHeightProperty().bind(container.heightProperty());
return container;
// Instead do something like the following:
// return new Region() {
// {
// getChildren().setAll(imageView);
// }
// @Override
// protected void layoutChildren() {
// imageView.setFitWidth(getWidth());
// imageView.setFitHeight(getHeight());
// }
// };
}
@Override
public void start(Stage stage) throws Exception {
WritableImage image = new WritableImage(1, 1);
image.getPixelWriter().setColor(0, 0, Color.BLUE);
ImageView imageView = new ImageView(image);
// for debugging:
imageView.boundsInLocalProperty().addListener((obs, oldBounds, newBounds) -> System.out.println(newBounds));
Node imageContainer = createImageHolder(imageView);
HBox root = new HBox(imageContainer);
Scene scene = new Scene(root, 400, 400);
addStyleToScene(scene);
stage.setScene(scene);
stage.show();
}
private void addStyleToScene(Scene scene) {
// external stylesheet added to the scene (adds 2 pixels padding to all direct child nodes of the root)
String css = """
.root > * {
-fx-padding: 2;
}
""";
scene.getStylesheets().add("data:text/css;base64," +
Base64.getEncoder().encodeToString(css.getBytes(StandardCharsets.UTF_8)));
}
public static void main(String[] args) {
launch(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment