【问题标题】:JavaFX HBox AlignmentJavaFX HBox 对齐
【发布时间】:2015-06-24 19:36:46
【问题描述】:

我一直在使用 JavaFX 开发软件,但我遇到了一个愚蠢但令人担忧的问题。

在代码的某些部分,我有一个HBox,其中包含三个项目:imagelabelVBox

问题是我想让image向左对齐,即在window的左边距旁边,而VBox向右对齐,即在window 的右边框,我不知道该怎么做。

我尝试使用VBox.setAlignment(Pos.RIGHT_CENTER),但没有成功。

【问题讨论】:

  • 请向我们展示您尝试的代码。
  • 直觉会说 HBox 只是按照您通过hbox.getChildren().addall( arg0, arg1, ... argk);将它们添加到 HBox 的顺序对它们进行排序

标签: java javafx alignment vbox hbox


【解决方案1】:

我认为最好的选择可能是从HBox 切换到BorderPane。它可以让您将物品贴在窗口的任何边缘。
另一种选择是GridPane。您可以选择列并将其“Halignment”属性更改为“RIGHT”。

顺便说一句,我建议在玩 JavaFX 的同时使用 JavaFX Scene Builder

【讨论】:

  • 是的,这似乎更好
  • @torina,很高兴能帮上忙。谢谢。 ;)
【解决方案2】:

当您想要将项目放置在布局的两个角时,这是最常见的对齐问题。

让我们说你想要:

HBox
  |
  ImageView (Left)
  Label (Center)
  VBox (Right)

我非常简单的解决方案是使用两个额外的Regions。介于 ImageView 和 Label 之间。另一个在 Label 和 VBox 之间。

HBox
  |
  ImageView (Left)
  Region
  Label (Center)
  Region
  VBox (Right)

这些区域必须将 HGrow 设置为 Priority.Always,这样如果您调整 HBox 的大小,这两个区域就会增长,同时保持其他元素不变位置。

FXML 示例

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.*?>

<HBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="94.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <ImageView fitHeight="150.0" fitWidth="140.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="http://www.imaginaformacion.com/wp-content/uploads/2010/06/JavaFx.png" />
         </image>
      </ImageView>
      <Region prefHeight="200.0" prefWidth="200.0" HBox.hgrow="ALWAYS" />
      <Label prefHeight="17.0" prefWidth="205.0" text="Label On the Center" />
      <Region prefHeight="200.0" prefWidth="200.0" HBox.hgrow="ALWAYS" />
      <VBox alignment="CENTER_RIGHT" prefHeight="94.0" prefWidth="200.0">
         <children>
            <Label prefHeight="17.0" prefWidth="200.0" text="Label Inside the VBox" />
         </children>
      </VBox>
   </children>
</HBox>

请注意两个区域中的HBox.hgrow="ALWAYS"

输出

【讨论】:

  • 谢谢!使用包含 ImageView 的 &lt;VBox&gt; 时遇到了类似的问题。我的控件在图像更改之间上下跳跃,使用&lt;Region VBox.hgrow="ALWAYS"/&gt; 解决了我的问题。 :)
  • 谢谢。我使用了相同的逻辑,如:Region filler = new Region(); HBox.setHgrow(filler, Priority.ALWAYS); 然后hbox.getChildren().addAll(left, filler, right);
  • 谢谢。这帮助我节省了一些时间
猜你喜欢
  • 2015-01-03
  • 2010-12-16
  • 1970-01-01
  • 2019-12-23
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 2012-08-25
  • 2016-09-08
相关资源
最近更新 更多