2014-05-10 189 views
5

我是javafx的新手,請耐心等待。所以我想要做的事情非常簡單,但無法弄清楚如何正確使用它。如何在一個窗格中居中節點javafx

目標:創建一個500×500的窗格。我想添加一個節點,在我們的情況下可以說圖像視圖包含200×200的圖像。我希望能夠添加圖像視圖到窗格並讓它居中。

ImageView view = new ImageView(); 

    Image img = new Image("test.png"); 
    view.setImage(img); 
    Pane pane = new Pane(); 
    pane.setMinWidth(500); 
    pane.setMinWidth(500); 
    pane.getChildren().add(view); 

任何意見讚賞, 謝謝, d

+0

爲什麼不能使用'StackPane','HBox'或VBox?如果你使用'Pos.CENTER',他們可以有自己的對齊設置,它將自動將兩個維度放在兩個維度上。 –

+0

整個想法是我有一個錨定窗格,然後我希望用戶能夠添加任何佈局(VBox,HBox或Stackpane)。但是,錨定窗格的大小會發生變化並且沒有首選大小。那麼你如何將它與任何你使用的佈局集中在一起。 – darewreck

+0

您提到的佈局選擇都可以解決上述問題。我很困惑。爲什麼你必須使用'AnchorPane'? –

回答

13

,你有兩個選擇:使用StackPane,而不是Pane(因爲可以用Pos

StackPane p = new StackPane(); 
p.setPrefSize(700,700); //set a default size for your stackpane 
Image img = new Image("test.png"); //create an image 
ImageView v = new ImageView(img); //create an imageView and pass the image 

p.getChildren().add(v); //add imageView to stackPane 
StackPane.setAlignment(v,Pos.CENTER_LEFT); //set it to the Center Left(by default it's on the center) 
stage.setScene(new Scene(p)); 
stage.show(); 

1)例如

2)您可以使用JavaFx Scene Builder,這是一個JavaFx的可視化佈局工具。 例如,如果我想創建一個Hbox佈局:

<?import java.lang.*?> 
<?import java.net.*?> 
<?import java.util.*?> 
<?import javafx.geometry.*?> 
<?import javafx.scene.*?> 
<?import javafx.scene.control.*?> 
<?import javafx.scene.effect.*?> 
<?import javafx.scene.image.*?> 
<?import javafx.scene.layout.*?> 
<?import javafx.scene.shape.*?> 
<?import javafx.scene.text.*?> 

<HBox alignment="CENTER" prefHeight="369.0" prefWidth="425.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" > 
    <children> 
     <ImageView fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" x="0.0" HBox.hgrow="NEVER"> 
      <image> 
       <Image url="@../yourImg.png" /> 
      </image> 
     </ImageView> 
    </children> 
</HBox> 

保存,它作爲myLayout.fxml主類中,並添加下列代碼:

Hbox root = FXMLLoader.load(getClass().getResource("myLayout.fxml")); 
Scene scene = new Scene(root); 
stage.setScene(scene); 
stage.show(); 
+1

謝謝。如果它是沒有首選大小的anchorPane會發生什麼。我試圖只將stackPane添加到錨窗格。但是,如果沒有設置所設定的大小,則居中將不起作用。在我的示例中,可以調整錨定窗格的大小,因爲左側,右側,頂部和底部是可以打開並可以更改中心錨定窗格大小的選項卡。 – darewreck

2

我通常用下面的辦法以節點/窗格爲中心:

<VBox alignment="CENTER"> 
    <HBox alignment="CENTER"> 
     <!-- your node/pane --> 
    </HBox> 
</VBox> 
相關問題