2015-04-17 68 views
8

我一直在使用JavaFX的軟件,我有一個愚蠢但令人擔憂的問題。JavaFX HBox Alignment

在代碼的某些部分,我有一個HBox,其中有三個項目:imagelabelVBox

的問題是,我想有image左對齊,就是旁邊window的左邊界,並VBox靠右對齊,就是旁邊的右邊界window,我不知道該怎麼做。我試過使用VBox.setAlignment(Pos.RIGHT_CENTER),但它不起作用。

+0

請告訴我們你的企圖代碼。 – Constant

+0

直覺會說,HBox只是通過'hbox.getChildren()。addall(arg0,arg1,... argk);' – Waterbagel

回答

4

我認爲最好的選擇可能是從HBox切換到BorderPane。它讓你可以將物品粘貼到窗口的任何邊緣。
另一種選擇是GridPane。您可以選擇列並將其'Halignment'屬性更改爲'RIGHT'。

而且,順便說一句,我建議在使用JavaFX的同時使用JavaFX Scene Builder

20

當您想要將項目放置到佈局的兩個角落時,這是最常見的對齊問題。

讓我們說你想有:

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"

輸出

enter image description here

+0

將它們添加到HBox中的順序來命令它們,謝謝!使用含有ImageView的''有類似的問題。我的控件在圖像變化之間跳來跳去,使用''解決了我的問題。 :) – Robula

+1

謝謝。我使用了相同的邏輯,如下所示: 'Region filler = new Region(); HBox.setHgrow(fill,Priority.ALWAYS);'然後'hbox.getChildren()。addAll(left,filler,right);' – Satyendra