我一直在使用 JavaFX 开发软件,但我遇到了一个愚蠢但令人担忧的问题。
在代码的某些部分,我有一个HBox
, 并且在其中三个项目: an image
, alabel
和 a VBox
。
问题是我想让image
左对齐,即在左边距旁边window
,和VBox
右对齐,即在右边框旁边,window
我不知道怎么做去做吧。
我试过用VBox.setAlignment(Pos.RIGHT_CENTER)
,但没有用。
当您要将项目放置在布局的两个角时,这是最常见的对齐问题。
让我们说你想要:
HBox
|
ImageView (Left)
Label (Center)
VBox (Right)
我很简单的解决方案是使用两个额外的Regions
. 介于 ImageView 和 Label 之间。另一个在 Label 和 VBox 之间。
HBox
|
ImageView (Left)
Region
Label (Center)
Region
VBox (Right)
这些 Regions 必须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"
在这两个地区。
输出
我认为最好的选择可能是从 切换HBox
到BorderPane
. 它让您可以将物品贴在您窗户的任何边缘。
另一种选择是GridPane
。您可以选择列并将其“Halignment”属性更改为“RIGHT”。
而且,顺便说一句,我建议在玩 JavaFX 的同时使用JavaFX Scene Builder 。