所以我有一个 StackPane。它的高度设置为 300。堆栈 Pane 内部是一个包含图像和标签的 ImageView 。我将图像高度设置为 250,并将对齐方式设置为顶部中心。我将标签对齐设置为 Pane 的底部中心。然而,每次我运行代码时,图像都会被推到框架的底部,标签文本位于其顶部,因此很难阅读。如果堆栈 Pane 的高度为 500,图像为 100 Pos.TOP-CENTER,并且标签为基线中心,则文本不会像预期的那样显示在图像下方,这并不重要。相反,它显示在图像的底部。有人能告诉我为什么会发生这种情况吗?
public class VBoxProductPane extends StackPane {
private MainController mainController;
private String name;
private Image image;
private String fileName;
private double price;
private int quantity;
private Button button = new Button();
private Product product;
public VBoxProductPane(Product product){
setPrefSize(250, 275);
this.name = product.getName();
this.price = product.getPrice();
this.quantity = product.getQuantity();
this.fileName = product.getFileName();
this.product = new Product(this.name, this.price, this.quantity, this.fileName);
setImage();
setButton();
setLabel();
setOnMouseEntered(e -> {
button.setVisible(true);
});
setOnMouseExited(e -> {
button.setVisible(false);
});
}
private void setButton(){
button.setText("Explore");
getChildren().add(button);
button.setVisible(false);
button.setOnAction(e -> {
button.setVisible(true);
});
button.setOnAction(e -> {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/ProductLayout.fxml"));
Stage secondaryStage = new Stage();
loader.setController(new ProductPage(mainController, product));
secondaryStage.setTitle(product.getName());
secondaryStage.setHeight(450);
secondaryStage.setWidth(600);
Scene scene = new Scene(loader.load());
secondaryStage.setScene(scene);
secondaryStage.show();
} catch (IOException ex) {
ex.printStackTrace();
}
});
}
private void setLabel(){
Label label = new Label(getLabelText());
setAlignment(label, Pos.BOTTOM_CENTER);
// this does nothing
label.setLayoutY(250);
label.setWrapText(true);
label.setTextAlignment(TextAlignment.CENTER);
getChildren().add(label);
setAlignment(label, Pos.BOTTOM_CENTER);
}
private String getLabelText(){
if (this.product.getName() == null){
System.out.println("name is null");
}
return this.product.getName();
}
private Image getImage(){
Image image = this.product.getImage();
return image;
}
private void setImage() {
ImageView imageViews = new ImageView();
imageViews.setImage(this.product.getImage());
setAlignment(imageViews, Pos.TOP_CENTER);
// this does nothing
imageViews.setFitHeight(150);
// does not matter what this height is set to
// image is always displayed at the bottom with text over top
imageViews.setFitWidth(250);
imageViews.setY(0);
getChildren().add(imageViews);
}
}
最佳答案
ImageView
是一种非常简单的Node
类型。它不可调整大小(它没有最小/最大/首选项值)。这使得它(不幸的是)在布局中使用非常尴尬。
例如,StackPane
无法就如何处理 ImageView
做出正确的决定(因为它没有首选大小,甚至没有最大大小)并为其分配尽可能多的空间。
可以采取以下措施来解决此问题:
1) 将 ImageView
包装在容器中并设置其尺寸(将最大尺寸设置为与适合尺寸相同)。
2) 使用VBox
或BorderPane
,以便您可以将Label
正确放置在底部。
3)使用Label
的setGraphic
将Image
直接与Label
控件集成。
关于java - 为什么我无法在图像下方显示标签(javafx)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56012861/