Java Magazine, September/October 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 57 javafx Java string Following this naming convention FXMLLoader will match field names to variable names and match field types to widget types Thus youll get a runtime exception if the field were to be defined as Choicebox String instead This potential error can be avoided if your IDE of choice is aware of FXML conventions JSR 330 defines the basic principles for performing dependency injection in a Java program The second feature is the definition of a public method whose name must be initialize and which takes no arguments This method is invoked by FXMLLoader after all widget injections have been performed This is the right time to perform data initialization because the widget references have been fully resolved and injected up to this point Thats precisely what happens in this example by filling the ListView with default data If the method were to be named something else FXMLLoader would not call it This is a hard constraint defined by the FXMLLoader conventions Finally you catch a glimpse of an action handler defined with a method whose name matches the value of the onAction handler associated with the button as you saw in the FXML file This handler reacts to the button being clicked thus it takes an ActionEvent as argument Make note of this type because it will change depending on the type of event you want the code to react to For example the argument should be of type MouseEvent if the code should react to mouse movements This event handler is called immediately as the button is clicked and its invoked inside the UI thread as well Thats not a problem for this trivial application because the handler simply adds a new item to the list However be aware of this setup because typically an application would open a network connection access a database or file or perform all sorts of computations that must be executed outside the UI thread When data is ready youll have to push it back to the UI elements inside the UI thread So be aware of the threading constructs provided by JavaFX if threading is done incorrectly you might get runtime exceptions an unresponsive application data corruption or worse In summary a controller is responsible for providing behavior to an FXML view and you establish a relationship between them using the fx controller attribute on the root node of an
You must have JavaScript enabled to view digital editions.