Java Reference
In-Depth Information
If the controller is not set, a LoaderException will be thrown, with a message “No controller specified.” This is
because we did specify the controller method actionHandler as the action event handler for both the text field and
the button. The FXMLLoader needs the controller to fulfill these specifications in the FXML file. Had the event handlers
not been specified, the FXML file would have been loaded successfully because there is no need for a controller.
This program is a very primitive web browser with an address bar TextField , a load Button , and a WebView .
Figure 3-4 shows the FXMLLoaderExample program at work.
Figure 3-4. The FXMLLoaderExample program
Our next example, ControllerFactoryExample, is nearly identical to the FXMLLoaderExample with only two
differences, so we do not show the complete code here. You can find it in the code download bundle. Unlike in
FXMLLoaderExample , we do specify fx:controller in the FXML file. This forces us to remove the setController() call in
the main class, because otherwise we get a LoadException with a message “Controller value already specified.” However,
because our controller does not have a default constructor, FXMLLoader will throw a LoadException caused by its inability
to instantiate the controller. This exception can be remedied by a simple controller factory that we set on the fxmlLoader :
fxmlLoader.setControllerFactory(
clazz -> new ControllerFactoryExampleController("ExampleController"));
Here we used a simple lambda expression to implement the functional interface Callback<Class<?>, Object> ,
which has a single
Object call(Class<?>)
method. In our implementation we simply return an instance of ControllerFactoryExampleController .
 
Search WWH ::




Custom Search