Getting Started With JavaFX Database Operations

3y ago
98 Views
30 Downloads
2.23 MB
51 Pages
Last View : 13d ago
Last Download : 1m ago
Upload by : Raelyn Goode
Transcription

Getting Started with JavaFX Database OperationsWhen I started to work in my current position, one of my task is to do manual operations forcampaign products every week. After the second week, I thought that I have to automate thistask using a GUI based desktop program instead of using some DB scripts manually. Then, Istarted to search which solution I should choose. Finally, I ended up my decision withJavaFX. This is the starting point of my JavaFX journey. In my JavaFX post series, I will tryto describe how to create a JavaFX application, how to use its core components, how tocommunicate with DB and so on.Before starting JavaFX post series, I want to thank Marko Jakob. I learned a lot stuff fromhis tutorial series and I suggest that check that tutorial series.Let’s get started!What is JavaFX?It is a next generation GUI toolkit and you can create rich GUI applications with JavaFX.You can also customize style using CSS and edit them with XML. Also, it includes a dragand drop design editor that is called as SceneBuilder. It is much easier to design GUIs withSceneBuilder. You can drag and drop GUI elements and then modify their style with CSS oredit them with XML. For more details please visit here.Prerequisites Install latest JAVA JDK 8 from here. Install IntelliJ, Eclipse or Netbeans IDE (I prefer IntelliJ) Install Scene Builder from here. Install Oracle Express Edition from here.Create a JavaFX ProjectOpen IntelliJ and click File - New Project and then click Java FX and click Next button.1

Type “First JavaFX Project” as Project name and set your Project Location as you wantand click Finish button.2

Thanks to IntelliJ, it automatically creates a JavaFX project structure and put a sampleHello World code into Main class.3

We are going to write our code based on MVC (Model-View-Controller) principle. Thus, Iused three (plus one “util” package) packages. These are controller, model, and view. Weshould move .fxml files into view package and controller classes in controller package. Also,I added one extra package and called it as util. It is for utility classes such as DBUtil fordatabase connection operations. “model” package comprises “model” and“DataAccessObject” classes. A sample application structure is shown below figure.Also, we need to set SceneBuilder path. To do this, go to File - Settings, type “JavaFX”in the search bar. Then, copy and paste SceneBuilder path as shown below and click OK.Also, please check this link.After setting the SceneBuilder path, go into sample.fxml file and right click, then you will see“Open in SceneBuilder” option. When you click this option, the selected fxml file will openin SceneBuilder. You can also check here.4

We have almost finished our setup. For our first example, we will use Oracle DB and defaultHR schema. In second post, we will do some DML (Database Manipulation) operationssuch as Create, Read, Update, Delete, Insert, etc. I also explained how to install and useOracle Express at the end of this post.Now, let’s go to our project’s view folder and create EmployeeOperations.fxml andRootLayout.fxml files manually. To do this, right click your mouse and create a new emptytext file and changed its name as EmployeeOperations.fxml (in next post, I will change itsname as EmployeeView.fxml) . Do the same for the RootLayout.fxml. If you want, you cando this with SceneBuilder. Finally, in view folder we will have these two .fxml files.Go to Windows Start and type SceneBuilder and then press Enter, then SceneBuilder willopen.After that, click “File - Open” and open EmployeeOperations.fxml file.5

Actually, there are two ways to design user interface. One of them is using IntelliJ tomanipulate .fxml file or using SceneBuilder to design the UI. Using SceneBuilder whencreating and designing UI at the first time is much easier and reasonable. I generally useintelliJ for manipulating UI at later stages.First, open EmployeeOperations.fxml file and drag and drop Anchor Pane into the middlepane of SceneBuilder.Then, if you want you can modify its properties by using right pane.6

You can use left pane’s Controls section to add TextField, Label, TextArea, and button todesign your UI as shown below. The below figure is the draft version of the UI, not the finalversion.7

You can also group UI elements. Select the UI elements that you want to group then go to“Arrange Wrap in” then click the appropriate choice. If elements are vertically listed, thenchose VBox. If they are horizontally listed, then chose HBox.8

After grouping those elements, you can change spaces of elements by using right paneLayout section’s Spacing option.Then, in order to use these components in the code, you should set fx:id values on the rightpane as shown below.If you want to set prompt text and default text you can use the Properties section on theright pane. You can change Prompt Text and Text values as shown below.While designing UI, you can check its status by typing Ctrl P.9

For more information about layout design, you should visit here andhttps://dzone.com/refcardz/javafx-8-1 (I suggest you to visit DZone. They explained layoutdesign very well.)Now, let’s design RootLayout. Open RootLayout.fxml with SceneBuilder.This time drag and drop BorderPane.Then, add to MenuBar into TOP slot.10

RootLayout’s final design is shown below.Our aim is to show EmployeeOperations.fxml into RootLayout.fxml. Now, I want toexplain JavaFX application structure briefly. Our generated Main class code is shownbelow.package sample;import javafx.application.Application;import javafx.fxml.FXMLLoader;import javafx.scene.Parent;import javafx.scene.Scene;import javafx.stage.Stage;public class Main extends Application {11

@Overridepublic void start(Stage primaryStage) throws Exception{Parent root e.fxml"));primaryStage.setTitle("Hello World");primaryStage.setScene(new Scene(root, 300, 275));primaryStage.show();}public static void main(String[fusion builder container hundred percent "yes"overflow "visible"][fusion builder row][fusion builder column type "1 1"background position "left top" background color "" border size "" border color ""border style "solid" spacing "yes" background image "" background repeat "norepeat" padding "" margin top "0px" margin bottom "0px" class "" id ""animation type "" animation speed "0.3" animation direction "left"hide on mobile "no" center content "no" min height "none"][] args) {launch(args);}}This is the default (generated) Main class and it extends Application class. It has start andmain methods. The key method is here start method. It is automatically called with stageparameter when application launched as you can see in main method.As you can see below figure, the main container is Stage and it consists of a scene andscene comprises all kinds of JavaFX elements such as text field, button, etc. All JavaFXapplications structure is like that. You can find more information here.If we change main class code as shown below, we can open Employee Operations viewinside of the RootLayout Border Pane. I tried to add comments and make the code moreunderstandable.package sample;import javafx.application.Application;12

import javafx.fxml.FXMLLoader;import javafx.scene.Scene;import javafx.scene.layout.AnchorPane;import javafx.scene.layout.BorderPane;import javafx.stage.Stage;import java.io.IOException;//Main class which extends from Application Classpublic class Main extends Application {//This is our PrimaryStage (It contains everything)private Stage primaryStage;//This is the BorderPane of RootLayoutprivate BorderPane rootLayout;@Overridepublic void start(Stage primaryStage) {//1) Declare a primary stage (Everything will be on this stage)this.primaryStage primaryStage;//Optional: Set a title for primary stagethis.primaryStage.setTitle("SW Test Academy - Sample JavaFX App");//2) Initialize RootLayoutinitRootLayout();//3) Display the EmployeeOperations ViewshowEmployeeOperationsView();}//Initializes the root layout.public void initRootLayout() {try {//First, load root layout from RootLayout.fxmlFXMLLoader loader new urce("view/RootLayout.fxml"));rootLayout (BorderPane) loader.load();//Second, show the scene containing the root layout.Scene scene new Scene(rootLayout); //We are sending rootLayout to theScene.13

primaryStage.setScene(scene); //Set the scene in primary stage.//Third, show the primary stageprimaryStage.show(); //Display the primary stage} catch (IOException e) {e.printStackTrace();}}//Shows the employee operations view inside the root layout.public void showEmployeeOperationsView() {try {//First, load EmployeeOperationsView from EmployeeOperations.fxmlFXMLLoader loader new urce("view/EmployeeOperations.fxml"));AnchorPane employeeOperationsView (AnchorPane) loader.load();// Set Employee Operations view into the center of root );} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {launch(args);}}Result:14

Note: Above UI design is the draft version and in next post, we will change and finalize it. Inthis post, I do not want to focus the final design of our UI.When you click any .fxml file in IntelliJ, you can see its content as shown below.Before start to coding, I want to explain how to install Oracle Express DatabaseFirst, you should visit this link and install Oracle Database Express Edition 11g Release 2.15

After you installing Oracle Express, please go to this link and UNLOCK HR sample useraccount. In this tutorial, we will use HR schema and its tables.Then, try to connect database with TOAD or Oracle SQL Developer. (I prefer TOAD)You can see how to connect DB with TOAD in below figure.16

Now, we are ready to start coding. In next post, we will use DAO (Data Access Object)Design Pattern and create EmployeeController controller (Business Class), Employeemodel (Employee Model), EmployeeDAO (Data Access Class) classes, and DBUtil class(DB Connection Utility) for DB connection operations.Sumber: javafx/17

Database Operations in JavaFXAt first, part of JavaFX tutorial series, we created a sample JavaFX project, designed the draftversion of the UI and set up an Oracle XE database. In this post, we will create controller,model, DAO, and Util classes to do DB operations. Before starting to code, I want to givemore information about our example project. The latest version of the UI is shown in thefigure below.You can design UI using SceneBuilder. After drag and drop any element to the anchor pane,you need to set their fx:id properties. These properties must be unique and you can useelements in your code with their unique fx:id properties. Also, you can copy paste anyelement on anchor pane then change its name and fx:id value. I demonstrated how to design aGUI in the figure below.18

I listed details of the example below: Search an employee using employee’s id and show the result on table view and text area.(SELECT) Search all employees and show them on the table view. (SELECT * FROM) Update the e-mail address of an employee by using employee’s id. (UPDATE) Delete an employee by using employee’s id. (DELETE) Insert a new employee to the “employee table”. (INSERT) Show results of all operations on the Text Area (Print on Result Console)We will use Oracle XE database and its default HR schema. In order to connect Oracle DB,we will use JDBC driver. JDBC driver is a software component enabling a Java applicationto interact with a database. To add JDBC driver in our project:1) Go to your project, right-click, and then click Open Module Settings.2) Click Libraries then click “ ” sign, click “From Maven”19

3) Write “odjbc” on search bar and enter. Then, select the “oracle:ojdbc6:11.2.0.3” andselect sources and JavaDocs click OK.4) Now, we can see ojdbc6:11.2.0.3 library in lib folder on IntelliJ.20

Finally, we are ready to start coding. As shown the picture below, I created 4 packages:controller, model, view and util.I used DAO Design Pattern to perform Employee operations. I want to explain DAO Patternbriefly, for more information, I suggest that you check Jakop Jenkov’s DAO tutorial. In DAOpattern, domain (business) logic does not directly communicate with the DB. Itcommunicates with DAO layer and DAO layer handles DB operations and sends the results tothe business layer.The philosophy under DAO pattern is that if you need to change the underlyingpersistence mechanism, you can do it in DAO layer, not all the places in the business layer.It is also very important that no details of underlying DB related mechanism leak out of DAOlayer to business layer.21

DBUtil ClassI want to start to explain the code with DBUtil class. In our example, DBUtil class isresponsible for DB connection, DB disconnection, database query and update operations.DAO Class (EmployeeDAO) uses DBUtil class’s methods to do higher-level DB operations.In DBUtil Class:– dbConnect() method connects to DB.– dbDisconnect() method closes DB connection.– dbExecuteQuery(String queryStmt) method executes given SQL statement and returnscachedRowSet set. In order to eliminate “java.sql.SQLRecoverableException: ClosedConnection: next” error we return cachedRowSet instead of ResultSet. Thus, we can usecachedRowSet in other classes and manipulate that data.– dbExecuteUpdate(String sqlStmt) method executes given Update, Insert, Delete SQLoperations.I tried to write explanatory comments in the code below. If you have questions please don’thesitate to write a comment. I will try to answer your questions.DBUtil Class Code:package sample.util;import com.sun.rowset.CachedRowSetImpl;import java.sql.*;/*** Created by ONUR BASKIRT on 22.02.2016.*/public class DBUtil {//Declare JDBC Driverprivate static final String JDBC DRIVER ate static Connection conn null;//Connection String//String connStr /Username HR, Password HR, IP localhost, IP 1521, SID xeprivate static final String connStr ct to DBpublic static void dbConnect() throws SQLException, ClassNotFoundException {//Setting Oracle JDBC Driver22

try {Class.forName(JDBC DRIVER);} catch (ClassNotFoundException e) {System.out.println("Where is your Oracle JDBC Driver?");e.printStackTrace();throw e;}System.out.println("Oracle JDBC Driver Registered!");//Establish the Oracle Connection using Connection Stringtry {conn DriverManager.getConnection(connStr);} catch (SQLException e) {System.out.println("Connection Failed! Check output console" e);e.printStackTrace();throw e;}}//Close Connectionpublic static void dbDisconnect() throws SQLException {try {if (conn ! null && !conn.isClosed()) {conn.close();}} catch (Exception e){throw e;}}//DB Execute Query Operationpublic static ResultSet dbExecuteQuery(String queryStmt) throws SQLException,ClassNotFoundException {//Declare statement, resultSet and CachedResultSet as nullStatement stmt null;ResultSet resultSet null;CachedRowSetImpl crs null;try {//Connect to DB (Establish Oracle Connection)dbConnect();System.out.println("Select statement: " queryStmt "\n");23

//Create statementstmt conn.createStatement();//Execute select (query) operationresultSet stmt.executeQuery(queryStmt);//CachedRowSet Implementation//In order to prevent "java.sql.SQLRecoverableException: ClosedConnection: next" error//We are using CachedRowSetcrs new CachedRowSetImpl();crs.populate(resultSet);} catch (SQLException e) {System.out.println("Problem occurred at executeQuery operation : " e);throw e;} finally {if (resultSet ! null) {//Close resultSetresultSet.close();}if (stmt ! null) {//Close Statementstmt.close();}//Close connectiondbDisconnect();}//Return CachedRowSetreturn crs;}//DB Execute Update (For Update/Insert/Delete) Operationpublic static void dbExecuteUpdate(String sqlStmt) throws SQLException,ClassNotFoundException {//Declare statement as nullStatement stmt null;try {//Connect to DB (Establish Oracle Connection)dbConnect();//Create Statementstmt conn.createStatement();//Run executeUpdate operation with given sql statementstmt.executeUpdate(sqlStmt);24

} catch (SQLException e) {System.out.println("Problem occurred at executeUpdate operation : " e);throw e;} finally {if (stmt ! null) {//Close statementstmt.close();}//Close connectiondbDisconnect();}}}Employee Class (Model)We need a model class to hold information about the employee. Add a new class to the modelpackage and called it Employee.This class holds all fields of the Employee such as name, last name, email, etc. It contains setand get methods and properties for all fields of a model class. A Property notifies us whenany variable such as name, last name, etc. is changed. This helps us keep the view in syncwith the data.You can see the all fields of the employee from database as shown below.Employee Class Code:package sample.model;import javafx.beans.property.*;import java.sql.Date;25

/*** Created by ONUR BASKIRT on 27.02.2016.*/public class Employee {//Declare Employees Table Columnsprivate IntegerProperty employee id;private StringProperty first name;private StringProperty last name;private StringProperty email;private StringProperty phone number;private SimpleObjectProperty Date hire date;private StringProperty job id;private IntegerProperty salary;private DoubleProperty commission pct;private IntegerProperty manager id;private IntegerProperty department id;//Constructorpublic Employee() {this.employee id new SimpleIntegerProperty();this.first name new SimpleStringProperty();this.last name new SimpleStringProperty();this.email new SimpleStringProperty();this.phone number new SimpleStringProperty();this.hire date new SimpleObjectProperty ();this.job id new SimpleStringProperty();this.salary new SimpleIntegerProperty();this.commission pct new SimpleDoubleProperty();this.manager id new SimpleIntegerProperty();this.department id new SimpleIntegerProperty();26

}//employee idpublic int getEmployeeId() {return employee id.get();}public void setEmployeeId(int employeeId){this.employee id.set(employeeId);}public IntegerProperty employeeIdProperty(){return employee id;}//first namepublic String getFirstName () {return first name.get();}public void setFirstName(String firstName){this.first name.set(firstName);}public StringProperty firstNameProperty() {return first name;}//last namepublic String getLastName () {return last name.get();27

}public void setLastName(String lastName){this.last name.set(lastName);}public StringProperty lastNameProperty() {return last name;}//emailpublic String getEmail () {return email.get();}public void setEmail (String email){this.email.set(email);}public StringProperty emailProperty() {return email;}//phone numberpublic String getPhoneNumber () {return phone number.get();}public void setPhoneNumber (String phoneNumber){this.phone number.set(phoneNumber);}28

public StringProperty phoneNumberProperty() {return phone number;}//hire datepublic Object getHireDate(){return hire date.get();}public void setHireDate(Date hireDate){this.hire date.set(hireDate);}public SimpleObjectProperty Date hireDateProperty(){return hire date;}//job idpublic String getJobId () {return job id.get();}public void setJobId (String jobId){this.job id.set(jobId);}public StringProperty jobIdProperty() {return job id;}29

//salarypublic int getSalary() {return salary.get();}public void setSalary(int salary){this.salary.set(salary);}public IntegerProperty salaryProperty(){return salary;}//commission pctpublic double getCommissionPct() {return commission pct.get();}public void setCommissionPct(double commissionPct){this.co

Database Operations in JavaFX . At first, part of JavaFX tutorial series, we created a sample JavaFX project, designed the draft version of the UI and set up an Oracle XE database. In this post, we will create controller, model, DAO, and Util classes to do DB operations. Before starting to code, I want to give more information about our example .

Related Documents:

.media - in Default VM Arguments. Note that your JavaFX library location can be different depending on the location that you unzipped. METHOD III: From CMD Prompt: java --module-path "C:\Users\selim\Documents\javafx-sdk-11.0.2\lib" --add-m

This tutorial is a compilation of three documents that were previously delivered with the JavaFX 2.x documentation set: JavaFX Overview, JavaFX Architecture, and Getting Started with JavaFX.

This chapter describes how to add JavaFX co ntent into a Swing application and how to use threads correctly when both Swing and JavaFX content operate within a single application. JavaFX SDK provides the JFXPanel class, which is located in the javafx.embed.swing package and enables you to embed

Oct 10, 2011 · Support for ARM platforms has also been made available with JavaFX 8. JDK for ARM includes the base, graphics and controls components of JavaFX. To install JavaFX install your chosen version of the Java Runtime environment and Java Development kit. Features offered by JavaFX include

What You Will Learn 1 1.1 Background Basics 2 JavaFX Integration 2 1.2 The NetBeans Platform: The Big Picture 3 Module System API 3 . 2.4 Improving the User Experience 63 2.5 Concurrency and Thread Safety 68 . 3.2 Building JavaFX Programs 87 Creating a JavaFX Application 88 Java APIs 88

Swing includes a . JFXPanel. class to embed JavaFX components into a Swing application, and JavaFX includes a . SwingNode. class to embed Swing components into a JavaFX application. Both classes provide corresponding API documentation. Additionally, the official Java documentation site includes an arti

General rules 8 Tecniche di programmazione A.A. 2020/2021 A JavaFX application extends javafx.application.Application The main() method should call Application.launch() The start() method is the main entry point for all JavaFX applications Called with a Stage connected to the Operating System's window The content of the scene is represented as a hierarchical

a group level, or would be more usefully reported at business segment level. In some instances it may be more appropriate to report separately KPIs for each business segment if the process of aggregation renders the output meaningless. For example it is clearly more informative to report a retail business segment separately rather than combining it with a personal fi nancial services segment .