我首先创建了3个fxml文件,然后是预加载器,然后是我的主应用程序。在预加载器期间,我加载数据库的东西和图像以及一些其他任务。
在预加载器中我创建了一个加载我的主应用程序的方法,如此
private void showMainProgram() throws IOException{
mainStage = new Stage();
FXMLLoader fxmlLoader = new FXMLLoader();
AnchorPane aplogin = fxmlLoader.load(getClass().getResource("Main.fxml").openStream());
MainController controller = (MainController) fxmlLoader.getController();
controller.setLoaderProperties(this);
Scene scene = new Scene (aplogin) ;
mainStage.setScene(scene);
mainStage.setTitle("loading");
mainStage.show();
}
现在发生的事情如下:
public class MainController implements Initializable {
public LoaderController loaderController ;
@FXML ListView mylist ;
@FXML Label labelName ;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
System.out.println("This will happen first (1)");
DoSomeStuff();
}
public void DoSomeStuff () {
System.out.println("This will happen next (2)");
// now here i will get a javafx.fxml.LoadException
//because my loadController is not yet set
labelName.setText(loaderController.UserDTO.getName());
}
public void setLoaderProperties(LoaderController loaderController) {
// I need this to happen first
System.out.println("This happens last (3)");
this.loaderController = loaderController ;
}
我试过这样的事情: 但我认为这会创建一个新的加载器控制器。所以我得到一个空例外。
public void initialize(URL url, ResourceBundle rb) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
VBox vboxLoader = fxmlLoader.load(getClass().getResource("loader.fxml").openStream());
LoaderController loadcontroller = (LoaderController) fxmlLoader.getController();
this.loaderController = loadcontroller;
} catch (IOException ex) {
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
DoSomeStuff();
}
答案 0 :(得分:0)
这解决了问题
public class MainController implements Initializable {
public LoaderController loaderController ;
@FXML ListView mylist ;
@FXML Label labelName ;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
System.out.println("This will happen first (1)");
}
public void DoSomeStuff () {
System.out.println("This will happen last(3)");
labelName.setText(loaderController.UserDTO.getName());
}
public void setLoaderProperties(LoaderController loaderController) {
// I need this to happen first
System.out.println("This wil happen next (2)");
this.loaderController = loaderController ;
// adding DoSomeStuff in the method setLoaderProperties
// fixed the problem
DoSomeStuff();
}