JavaFX:如何使 ImageView 在窗格中居中

JavaFX: How to center an ImageView in a Pane

JavaFX:如何使 ImageView 在窗格中居中

你好, 我正在尝试根据当前 Window 大小将 ImageView 居中并调整其大小。

如果我将 ImageView 放入窗格中,我无法将其居中。 如果我改为将其放入 StackPane,则无法调整图像大小。

知道吗,我做错了什么? Google帮不了我。

使用窗格提取 FXML

      <HBox prefHeight="100.0" prefWidth="200.0" VBox.vgrow="ALWAYS">
       <children>
         <Button maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false" prefHeight="2000.0" prefWidth="100.0" text="Button" HBox.hgrow="ALWAYS" />
         <Pane fx:id="paneMainImage" prefHeight="200.0" prefWidth="200.0" HBox.hgrow="ALWAYS">
            <children>
               <ImageView fx:id="imageMainImage" fitHeight="10.0" fitWidth="10.0" pickOnBounds="true" preserveRatio="true" />
            </children>
            <HBox.margin>
               <Insets />
            </HBox.margin>
         </Pane>
         <Button maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false" prefHeight="2000.0" prefWidth="100.0" text="Button" HBox.hgrow="ALWAYS" />
        </children>
      </HBox>

这里是 Java 代码

public class FXMLDocumentController implements Initializable {

@FXML
Pane paneMainImage;

@FXML
ImageView imageMainImage;

@Override
public void initialize(URL url, ResourceBundle rb) {
    Image i = new Image(getClass().getResource("resources/DSC_0168.JPG").toString());
    paneMainImage.getWidth();
    paneMainImage.getHeight();
    imageMainImage.setImage(i);
    imageMainImage.fitWidthProperty().bind(paneMainImage.widthProperty());
    imageMainImage.fitHeightProperty().bind(paneMainImage.heightProperty());
}
}

与 StackPane 相似的代码

 <HBox prefHeight="100.0" prefWidth="200.0" VBox.vgrow="ALWAYS">
     <children>
        <Button maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false" prefHeight="2000.0" prefWidth="100.0" text="Button" HBox.hgrow="ALWAYS" />
        <StackPane fx:id="paneMainImage" prefHeight="150.0" prefWidth="200.0" HBox.hgrow="ALWAYS">
           <children>
              <ImageView fx:id="imageMainImage" fitHeight="10.0" fitWidth="10.0" pickOnBounds="true" preserveRatio="true" />
           </children>
        </StackPane>
        <Button maxWidth="-Infinity" minWidth="-Infinity" mnemonicParsing="false" prefHeight="2000.0" prefWidth="100.0" text="Button" HBox.hgrow="ALWAYS" />
     </children>
  </HBox>

Java

public class FXMLDocumentController implements Initializable {

@FXML
StackPane paneMainImage;

@FXML
ImageView imageMainImage;

@Override
public void initialize(URL url, ResourceBundle rb) {
    Image i = new Image(getClass().getResource("resources/DSC_0168.JPG").toString());
    paneMainImage.getWidth();
    paneMainImage.getHeight();
    imageMainImage.setImage(i);
    imageMainImage.fitWidthProperty().bind(paneMainImage.widthProperty());
    imageMainImage.fitHeightProperty().bind(paneMainImage.heightProperty());
}
}

上也有类似的讨论。您是否尝试过使用那里讨论的任何解决方案(按复杂程度排序)?

  1. 使用 BorderPane 作为图像的父级使其居中使用

  2. setX 和 setY 方法明确设置图像的位置