2013-10-29 38 views
5

我需要在同一個Scene中顯示一個Panel並附加選項,當我單擊Button時,但我不知道如何實現此行爲。 Stage當我將面板添加到根VBox時沒有調整大小的問題。JavaFX:在將子項添加到根父項後自動調整階段

我寫了簡單的代碼來演示這個問題。

import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.Label; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 

public class Main extends Application { 
    public static void main(String[] args) { 
     launch(args); 
    } 

    public void start(Stage stage) throws Exception { 
     final VBox root = new VBox(); 
     Button button = new Button("add label"); 
     root.getChildren().add(button); 

     button.setOnAction(new EventHandler<ActionEvent>() { 
      public void handle(ActionEvent event) { 
       root.getChildren().add(new Label("hello")); 
      } 
     }); 

     stage.setScene(new Scene(root)); 
     stage.show(); 
    } 
} 

我想我需要調用一些方法來通知根容器做佈局,但我嘗試並沒有把所有的方法我想要的結果。

回答

24

程序工作

如您所願,我認爲你的程序工作差不多(當您單擊「添加標籤」按鈕,一個新的標籤添加到場景)。

爲什麼你不能看到它的工作

你無法看到新添加的標籤爲一個階段是默認大小以適應場景的初始內容。當您向場景添加更多區域時,舞臺不會自動調整大小以包含新區域。

怎樣做才能看到它的工作

添加標籤後,手動調整階段窗口。

OR

的初始大小爲場景設置,這樣就可以看到新添加的標籤。

stage.setScene(new Scene(root, 200, 300)); 

OR

後每添加一個新的標籤,size the stage to the scene

stage.sizeToScene(); 
0

只是改變了代碼

button.setOnAction(new EventHandler<ActionEvent>() 
{ 
    public void handle(ActionEvent event) 
    { 
     root.getChildren().add(new Label("hello")); 
     stage.sizeToScene(); 
    } 
});