如何在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 theImageViewsits on top and theTextfalls directly below it.alignment="CENTER": This ensures both the image and text are horizontally centered within theVBox, 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

