我正在使用SceneBuilder来创建我的程序视图。我需要在GridPane节点(单元格)中有图像,但问题是它们应该适合单元格。
换句话说,只要我调整应用程序窗口的大小,gridPade就会相应调整大小,但单元格内的图像会保持固定的大小。让应用程序窗口及其所有元素可调整大小是我的要求,因此我无法以不同的方式管理视图。
答案 0 :(得分:1)
使用ImageView.fitWidth
和ImageView.fitHeight
设置图片大小。假设您GridPane
的孩子延伸Region
,您可以使用layoutChildren
方法执行此操作:
public class ImageCell extends Region {
private final ImageView imageView;
public ImageCell(Image image) {
imageView = new ImageView(image);
getChildren().add(imageView);
}
public ImageCell() {
this(null);
}
public final void setImage(Image value) {
imageView.setImage(value);
}
public final Image getImage() {
return imageView.getImage();
}
public final ObjectProperty<Image> imageProperty() {
return imageView.imageProperty();
}
@Override
protected void layoutChildren() {
super.layoutChildren();
Insets insets = getInsets();
double x = insets.getLeft();
double y = insets.getTop();
double width = getWidth() - x - insets.getRight();
double height = getHeight() - y - insets.getBottom();
Image image = getImage();
double imageWidth = 0;
double imageHeight = 0;
if (image != null) {
imageWidth = image.getWidth();
imageHeight = image.getHeight();
}
// scale ImageView to available size
double factor = Math.min(width / imageWidth, height / imageHeight);
if (Double.isFinite(factor) && factor > 0) {
imageView.setFitHeight(factor * imageHeight);
imageView.setFitWidth(factor * imageWidth);
imageView.setVisible(true);
} else {
imageView.setVisible(false);
}
// center ImageView in available area
layoutInArea(imageView, x, y, width, height, 0, HPos.CENTER, VPos.CENTER);
}
}
要填充该区域,您需要确保GridPane
增长孩子:
@Override
public void start(Stage primaryStage) throws Exception {
GridPane gridPane = new GridPane();
RowConstraints rowConstraints = new RowConstraints();
rowConstraints.setPercentHeight(50);
ColumnConstraints columnConstraints = new ColumnConstraints();
columnConstraints.setPercentWidth(50);
gridPane.getRowConstraints().addAll(rowConstraints, rowConstraints);
gridPane.getColumnConstraints().addAll(columnConstraints, columnConstraints);
gridPane.addRow(0, new ImageCell(new Image("https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/se/se-icon.png")),
new ImageCell(new Image("https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png")));
gridPane.addRow(1, new ImageCell(new Image("https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/sf/sf-icon.png")),
new ImageCell(new Image("https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/su/su-icon.png")));
primaryStage.setScene(new Scene(gridPane));
primaryStage.show();
}