--- title: Database Systems Pre-Lab 8 Part I --- <h1 style='border: none'><center>Database Systems Pre-Lab 8 Part I</center></h1> <h2 style='border: none'><center>JDBC Part II</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 & Rasha E. Kahil<span style="float:right">2023/04/16</span></h6> --- ## Expecteed outcomes 1. To be familiar with JavaFX, build first FXML application with user interfaces for manipulating data. 2. To explore more about JDBC API statements and resultsets. ## Lab 8: Time and Plan | Tasks | Timing | | -------- | -------- | | Quiz 8 | 10 min | | Task 1 | 80 min | # Introduction Last pre-lab, with the help of the JDBC API, we connected to the database, ran queries on it, added data, updated data, and even deleted data very easily. We developed a simple java application that used the command line to take super simple queries from users and view the requested results in very simple way. In this pre-lab, we will continue exploring the JDBC API, and we will develop more interactive applications. We will use JavaFX to build graphical user interface. And we will introduce you to the very helpful MVC design pattern. # Create JavaFX Project 1. Create new JavaFX Project. ![](https://i.imgur.com/S4GVLGj.png) 2. Run `main()` method. ![](https://i.imgur.com/3zSdvKe.png) 3. Try to click the `Hello!` Button. Now your project configured to develop and run JavaFx. 👍 <center> ![](https://i.imgur.com/of2Y2w7.png) </center> # 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. # Scene Builder In this lab we use Scene Builder to build our user interfaces in a very friendly way. Scene Builder is a drag-and-drop user interface builder designed from the ground up for building high quality JavaFX user interfaces. It generates FXML files as output, allowing for separation between the design and development processes. # 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 query 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. ## 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 database query handlers, and classes for defining application entities. ## 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 navTo(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 void navToEnrollStudent(){ navTo(rootPane, "/app/views/enrollstudent.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/Test_JavaFX.git`, then press `Clone` and then `Trust Project`. ![](https://i.imgur.com/t2wfpaH.png) 3. Change the database configuration in `com/example/test_javafx/models/DBModel.java`. ![](https://i.imgur.com/leWDqZL.png) 4. Run the `Main.java` class. ![](https://i.imgur.com/dy5CAGl.png) ## Try to build the project yourself You are in the right point to build your first interactive application and use your practical database skills to manipulate and drive data. So, Let’s begin! Build the following interfaces using Scene Builder, write all required database query handlers in a model class, then control the UI constructs behaviors and the flow of data in views controllers. Our example project performs 3 main tasks: 1. Add a new Section of a particular course, 2. show lecture times for a particular student/instructor, and 3. enroll a new student. <center> ![](https://i.imgur.com/tmWA5fJ.png =500x) </center> In order to add a section for a specific course, we choose the ID of the course, select a building, then select room number from rooms of the selected building, notice the dependency of rooms on the building we choose; we can’t select a room until we select a building. Also, we select a year, semester, and a time slot too. <center> ![](https://i.imgur.com/6EDqult.png =500x) </center> To view the timetable for a student we checkbox ‘student’, if we do not check this checkbox, we are telling the application that we are querying a timetable of an instructor. We then enter the ID and press enter. After pressing enter, the name and department of the student/instructor will be shown. Depending on the student/instructor enrollment/teaching records, the lists of years and semesters will be set. After selecting the year and semester, we can press view to view the timetable. The timetable shows the lectures times of the selected semester. the column “Time Slot” in the table will contain the days, start and end times of the lectures as shown below. <center> ![](https://i.imgur.com/C88WYqy.png =500x) </center> ###### tags: `Database Systems` `Pre-Lab` `IUG` `Computer Engineering` <center>End Of Pre-Lab 8 Part I</center>