窗格 - > Hbox - > ImageView适合身高

时间:2018-01-22 16:06:17

标签: java user-interface javafx javafx-8 javafx-2

我在Pane内部的HBox中有ImageView,并且在调整大小阶段时希望ImageView高度适合HBox高度。尝试以下代码

package sample;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();
        pane.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
        HBox hBox = new HBox();
        hBox.setBackground(new Background(new BackgroundFill(Color.GREEN, CornerRadii.EMPTY, Insets.EMPTY)));
        hBox.setPrefHeight(100);
        hBox.setPrefWidth(100);
        hBox.prefHeightProperty().bind(pane.heightProperty());
        ImageView imageView = new ImageView("http://www.calgary.ca/CA/city-manager/scripts/about-us/webparts/images/ourHistory_retina.jpg");
        imageView.fitHeightProperty().bind(hBox.heightProperty());
        imageView.setPreserveRatio(true);
        hBox.getChildren().add(imageView);
        pane.getChildren().add(hBox);
        primaryStage.setScene(new Scene(pane, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

启动时,ImageView不适合窗口高度,它以原始大小显示。当我调整窗口大小以使其变大时,它只会缩放,然后是原始图像大小。

我也看到,hBox.prefHeightProperty().bind(pane.heightProperty())完美无缺(图像后面的红色HBox背景高度对应窗口高度)。

所以似乎imageView.fitHeightProperty().bind(hBox.heightProperty())表现得并不像我期望的那样。

如何使ImageView适合HBox的高度,嵌套在窗格中?

2 个答案:

答案 0 :(得分:1)

在您发布的代码中,HBox实际上比包含它的根Pane更高(虽然它被剪裁,因此您只能看到根侧的部分)。因此fitHeight上的绑定表现得如你所愿,但相对于HBox首选高度的布局并没有达到预期效果。因此,您需要更好地控制HBox的布局。

允许您最大程度控制的布局窗格是GridPane。因此,尽管可能有更简单的方法来执行此操作,但使用GridPane作为根并将HBox放在0,0的唯一单元格中可以控制{{1}的方式调整大小。这里唯一需要的是让HBox无限期缩小HBox

我认为以下内容提供了您想要的行为:

setMinHeight(0)

答案 1 :(得分:0)

感谢 James_D ,他们提出了解决方案。它甚至可以作为root用户保持Pane。

唯一要添加的行是

hBox.setMinHeight(0);

也奇怪

hBox.setPrefHeight(100);
hBox.setPrefWidth(100);

应该删除。

相关问题