--- title: Computer Programming II Pre-Lab 10 --- <h1 style='border: none'><center>Computer Programming II Pre-Lab 10</center></h1> <h2 style='border: none'><center>JavaFX Modules & MVC Design Pattern</center></h2> <h5><center>The Islamic University of Gaza<br>Engineering Faculty<br>Department of Computer Engineering</center></h5> <h6>Authors: Usama R. Al Zayan<span style="float:right">2023/05/03</span></h6> <h6>Parts of this Lab were adapted from work done by Mohammed Nafiz ALMadhoun and Mohammed AlBanna</h6> --- --- # JavaFX Modules in use ## `javafx.base` Defines the base APIs for the JavaFX UI toolkit, including APIs for bindings, properties, collections, and events. The following are some of its packages we will use: ### `javafx.collections` Contains the essential JavaFX collections and collection utilities. ### `javafx.event` Provides basic framework for FX events, their delivery and handling. ## `javafx.controls` Defines the UI controls, charts, and skins that are available for the JavaFX UI toolkit. The following is its main package that we will use: ### `javafx.scene.control` The JavaFX User Interface Controls are JavaFX components which provide some kind of control functionality inside a JavaFX application. JavaFX has a wide range of built-in controls. In this pre-lab, we will cover many controls such as: Label, CheckBox, TextFeild, Button, TableView, ImageView, and more. For a control to be visible it must be attached to the scene graph of some Scene object, so, controls are usually nested inside some JavaFX layout component that manages the layout of controls relative to each other. ## `javafx.graphics` Defines the core scenegraph APIs for the JavaFX UI toolkit (such as layout containers, application lifecycle, shapes, transformations, canvas, input, painting, image handling, and effects), as well as APIs for animation, css, concurrency, geometry, printing, and windowing. ## `javafx.fxml` Defines the FXML APIs for the JavaFX UI toolkit. Contains classes for loading an object hierarchy from markup. FXML is a scriptable, XML-based markup language for defining the user interface of a JavaFX application, since the hierarchical structure of an XML document closely parallels the structure of the JavaFX scene graph. # MVC Design Pattern **Model-View-Controller (MVC)** was one of the seminal insights in the early development of graphical user interfaces, and it is one of the first approaches to describing and implementing software constructs in terms of their responsibilities. **MVC** design pattern divides the application into three parts that are independent from each other. These designs are used to distinguish the presentation of data from the way the data is accepted from the user to the data that is being shown. In addition to dividing the application into these components, the MVC design defines the interactions between them. The functions of the three parts are: ## Model The central component of the pattern. The Model doesn’t contain any information on how to show the data to the user. **It is independent of the user interface.** It manages the data, logic and rules of the application. The Model receives user input from the controller as clean and clear calls stripped from any user clatter. For e.g., our data saving methods will be represented in the model component. ## View The view name is given to any presentation of information of the model in a particular format. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants. For e.g., our FXML files will be represented in the view component. ## Controller Most of the work is done by the controller. It receives and optionally validates input and converts it to commands for the model or view. It responds to the user input and performs interactions on the data model objects. ## How does MVC Design Pattern make working so easy? MVC helps in managing the code. The components created using the MVC design pattern are independent of each other in nature, and the separation of these components helps to develop reusable codes and help in parallel development. This makes working easier and simpler. # FXML project ## Models Our models is Java classes that contain all the data saving handlers, and classes for defining application objects. ## Views As we mentioned, we will adopt Scene Builder for designing user interfaces, which are built as FXML documents. Things to concern about the FXML: 1. `fx:id` attribute, which is assigned to view construct that will be accessed by controller. 2. `fx:controller` attribute, specifies the view controller, that is for each view there is a controller. The association between the FXML view and the controller class is made by specifying the class name as the value of the in the root element of the FXML. 3. `onAction=”#XXX”` attribute, which register an event handler for this construct. ## Controllers Whereas the user interface of an FXML application is defined inside an FXML document, all the logic to handle input events are written inside a controller class. You will spend most of your development time in controllers. Creating a controller for the view and model is relatively straight forward. Controllers contain instances of models to access their methods. Controllers also define UI controls for FXML elements and methods for event handlers. In a Controller, we initialize states and content using the `initialize()` method. ### UI controls In controller, we create UI control objects corresponding to the elements defined in the corresponding view’s FXML file. We use `@FXML` annotation, which binds to an `fx:id` attribute as follows: @FXML Label labelName; ← variable name must match fx:id ### Event handlers Event handlers are registered with any elements in the FXML file with `onXXX = “#...”` properties defined. These event handlers invoke the specified methods in the controller class, so for each event handler we specify a method in the controller class, for example, if there is a Button has `onAction=“#handleBtnAction”`, and the controller defines a method: @FXML private void handleButtonAction (ActionEvent event) { ... } When an action is fired on the button (e.g. the user presses it), this method is invoked. The method must have void return type, and can either define a parameter matching the event type (ActionEvent in this example), or can define no parameters. ### `initialize()` The `initialize()` method can either take no parameters, or can take a URL and a ResourceBundle. In the latter case, these parameters will be populated by the URL representing the location of the FXML file, and any ResourceBundle set on the FXMLLoader via loader.setResources(..). Either of these can be null if they were not set. ### Binding components ![](https://i.imgur.com/Y5ncb7w.png) The execution of the program begins with the Main class, which invokes the FXML loader. The FXML loader parses the FXML document, instantiates the nodes specified in the document, and builds the scene graph. After building the scene graph, the FXML loader instantiates the controller class, injects the fields defined in the controller class with objects instantiated from the FXML document and then calls the controller’s `initialize()` method. ```java= public class HelloApplication extends Application { @Override public void start(Stage stage) throws IOException { FXMLLoader fxmlLoader = new FXMLLoader (HelloApplication.class.getResource("hello-view.fxml")); Scene scene = new Scene(fxmlLoader.load(), 320, 240); stage.setTitle("Hello!"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } } ``` ### `FXMLLoader.load()` The load method performs several actions, and is useful to understand the order in which they happen: 1. The `FXMLLoader` reads and parses the FXML file. And since the root element of the FXML file defined a `fx:controller` attribute, the `FXMLLoader` creates a new instance of the controller class that it specifies. This happens by invoking the constructor on the class specified to create an object from `FXMLLoader`. 2. Any elements with `fx:id` attributes defined, which have fields in the controller with matching field names, are "injected" into those corresponding fields. 3. Any elements with `onAction=”#...”` attributes, which have methods in the controller with matching methods names, are "injected" into those corresponding methods. The `@FXML` annotation is mandatory for private member fields of the controller class, otherwise, field injection won’t work. However, it can be omitted for public fields. About the fields annotated with `@FXML`, a clever question is “are they accessible in the constructor”? >>> The answer is no. 4. Finally, if the controller class defines an `initialize()` method, this method is invoked by load method. Notice this happens after the `@FXML` fields have been injected, so they can be safely accessed in this method and will be initialized with the instances corresponding to the elements in the FXML file. ### Nested Controllers There is no need to create the whole UI in a single FXML using a single controller. The `<fx:include>` tag can be used to include one FXML file into another. The controller of the included FXML can be injected into the controller of the including file just as any other object created by the FXMLLoader. This is done by adding the `fx:id` attribute to the `<fx:include>` element. This way the controller of the included FXML will be injected to the field with the name `<fx:id value>` Controller. ### Navigate between views Navigation can be performed using actions on buttons or by any other actions and conditions. To perform navigation, we use FXMLLoader, see the following methods: ```java= public void navigateTo(Parent rootPane, String pathFxml) { try { Parent root = FXMLLoader.load(getClass().getResource(pathFxml)); rootPane.getScene().setRoot(root); } catch(IOException e){ System.out.println(e.getMessage()); } } ``` ```java= @FXML AnchorPane rootPane; @FXML public void onShowStudents(ActionEvent actionEvent) { navigation.navigateTo(rootPane, "views/showStudents.fxml"); } ``` Next, for each construct you use in your FXML views, there is a built-in JavaFX UI control available in the JavaFX API. All you need to do is to search in and explore the [documentation](https://openjfx.io/javadoc/19/index.html), it provides code samples and applications that illustrate how a particular UI control functions. We encourage you to treat the documentation as your good friend during your time with JavaFX. # Example project ## Clone a Project from GitHub 1. Create new project from Version Control. ![](https://i.imgur.com/FxcqItC.png) 2. Paste the repository link `https://github.com/UsamaZayan/OOP_JavaFX_Example.git`, then press `Clone` and then `Trust Project`. ![](https://i.imgur.com/t2wfpaH.png) 3. Run the `Main.java` class. ## Try to build the project yourself You are in the right point to build your first interactive application and use your practical OOP and Files skills to manipulate and drive data. So, Let’s begin! Build the following interfaces using Scene Builder, then control the UI constructs behaviors and the flow of data in views controllers. Our example project performs 2 main tasks: 1. Add a new Student, 2. show all Students. <center> ![](https://i.imgur.com/IWtLDGZ.png =300x) </center> In order to add a Student, Click `Add Student`. <center> ![](https://i.imgur.com/HeWzr3z.png =300x) </center> A popup window will appear to inform the operation is done. <center> ![](https://i.imgur.com/Cmhlbu4.png =300x ) </center> To return to the main interface, press the `back` button. In order to Show all Students, Click `Show Students`. <center> ![](https://i.imgur.com/TaLWYrz.png =300x) </center> ## Save Students when we close the App (Additional) When the program is closed, a pop-up window will appear to confirm the process of saving student data. All students will be saved in a save file if you click the `Save` button. The students will not be saved if you click on `Don't save`. Finally, if you press `Cancel`, the close operation will be cancelled (the data will not be saved either). <center> ![](https://i.imgur.com/dXnPyNs.png =300x) </center> ###### tags: `Computer Programming II` `Pre-Lab` `IUG` `Computer Engineering` <center>End Of Pre-Lab 10</center>