I want to use Netbeans Java FX with Scene builder for a measurement application. I have designed a scene with controls. I can handle the events from the UI-controls within the '...Controller.java'.

The 'controller' is the standard piece of code that is referenced in the XML file and gets initialized by the system with:

public void initialize(URL url, ResourceBundle rb) { ..

My problem: how do I access my central, persisting, 'model' objects from within the controller? Or, to be more exact, from the event handlers created within the controller initialize function.

The 'model' object would be created within the application object.

The solution must be trivial, but I have not found a way to

  • either access the Application from the controller
  • or access the controller from within the Application. What am I missing?

(the next question would be how to access the tree of panes within the object hierarchy created by screen builder, e.g. for graphics manipulation on output. Since the objects are not created by own code I can not store references to some of them. Ok, they could perhaps be found and referenced by tree-walking, but there must be a better way!)

Thanks for all insights!

有帮助吗?

解决方案

I have used the 2nd approach (access the controller from within the Application) for awhile ago similar to following. In Application class:

//..
private FooController fooController;
private Pane fooPage;
private Model myModel;

@Override
public void start(Stage stage) {
    //..
    myModel = new Model();
    getFooController().updateModel(myModel);
    //..
    Button button = new Button("Update model with new one");
    button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                Model myNewModel = new Model();
                getFooController().updateModel(myNewModel);
            }
    }
    // create scene, add fooPage to it and show.
}

private FooController getFooController() {
    if (fooController == null) {
       FXMLLoader fxmlLoader = new FXMLLoader();
       fooPage = fxmlLoader.load(getClass().getResource("foo.fxml").openStream());
       fooController = (FooController) fxmlLoader.getController();
    }
    return fooController;
}

Actually the first and second parts of your question is answered JavaFX 2.0 + FXML. Updating scene values from a different Task to the similar question of yours.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top