2013-11-20 239 views
1

如何在JavaFX中使用FXML創建自定義對話框?如何在JavaFX中使用FXML創建自定義對話框?

在過網樣品我看到大多像這樣

@Override 
public void start(Stage stage) throws Exception { 
    Parent root = 
     FXMLLoader.load(
     getClass().getResource(getClass().getSimpleName() + ".fxml")); 
    Scene scene = new Scene(root); 

FXML從加載的應用start()內並建立根節點。

但是如果我延長舞臺呢?從FXML加載哪裏?在構造函數中?或在initStyle()?或者在其他方法?

回答

1

你可以在你的主類使用下面的代碼:

FXMLLoader loader = new FXMLLoader(getClass().getResource("Sample.fxml")); 
Parent root = (Parent)loader.load(); 

//Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));   
Scene scene = new Scene(root);   
stage.setScene(scene); 
stage.show(); 

SampleController controller = (SampleController)loader.getController(); 
controller.setStageAndSetupListeners(stage); 

這SampleController後做一個函數setStageAndSetupListeners(),它會接受你的舞臺,現在你很容易地使用它。

+1

爲什麼這麼多行?是否可以設計對話框,以便可以用1-2行代碼調用它? –

+0

你必須得到Loader,以便你可以使用stage並傳遞另一個fxml來進行主Dialog到子Dialog之間的相互通信。 –

+0

'父根=(父)loader.load();'可以寫'父根=加載器。 load();' – Aerospace

相關問題