You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FXML中实现文本精准对齐到图片正下方?

Alright, I see the issue here—your current setup uses an <HBox>, which arranges elements horizontally, so the text ends up next to the image instead of directly below it. Let's fix this with a straightforward adjustment to your layout structure:

The Fix: Use a VBox for Vertical Alignment

Instead of placing the ImageView and Text directly in the outer HBox, wrap each image-text pair in a <VBox>. A VBox arranges elements vertically, which is exactly what we need to get the text under the image. We'll also add alignment settings to ensure the text is perfectly centered beneath the image.

Here's your modified FXML code:

<HBox xmlns:fx="http://javafx.com/fxml" fx:controller="sample.AudioButtonController" >
    <padding>
        <Insets topRightBottomLeft="30" />
    </padding>
    <children>
        <!-- Wrap each image + text pair in a VBox -->
        <VBox alignment="CENTER" spacing="5">
            <ImageView fitHeight="120" fitWidth="120" fx:id="image" onMousePressed="#mousePressed">
            </ImageView>
            <Text fx:id="text"/>
        </VBox>
        <!-- When looping, you'll add more VBox elements here for each image-text pair -->
    </children>
</HBox>

Key Details Explained:

  • <VBox>: This container stacks its child elements vertically, so the ImageView sits on top and the Text falls directly below it.
  • alignment="CENTER": This ensures both the image and text are horizontally centered within the VBox, guaranteeing the text lines up perfectly under the image's center.
  • spacing="5": An optional setting to add a small gap between the image and text (adjust the number to your preferred spacing).

For Your Java Loop Code

If you're generating these image-text pairs dynamically in Java, make sure to create a new VBox for each pair, then add that VBox to your outer HBox. Here's a quick example snippet:

// Assume your outer HBox is referenced as hBoxContainer
HBox hBoxContainer = ...;

for (int i = 0; i < yourImageList.size(); i++) {
    // Create ImageView
    ImageView imageView = new ImageView(new Image(yourImageList.get(i)));
    imageView.setFitHeight(120);
    imageView.setFitWidth(120);
    imageView.setOnMousePressed(this::mousePressed);

    // Create Text
    Text text = new Text(yourTextList.get(i));

    // Build the vertical pair container
    VBox imageTextPair = new VBox(imageView, text);
    imageTextPair.setAlignment(Pos.CENTER);
    imageTextPair.setSpacing(5);

    // Add to outer horizontal container
    hBoxContainer.getChildren().add(imageTextPair);
}

This setup will give you the exact "text directly below each image" alignment you're looking for, just like the <figure>/<figcaption> pattern in HTML5!

内容的提问来源于stack exchange,提问作者user13600214

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:32:58