MySQL Database and Java Desktop GUI
MySQL Database and Java Desktop GUI
http://www.javaguicodexample.com/javadesktopguidatabaseappsdev.html
In this series of three parts, we will learn how to build Java desktop GUI
application that connected to MySQL database. This tutorial is quite long
containing a lot of screen snapshots to make it as details as possible. The
original tutorial can be found at netbeans.org. All credits must go to the original
authors.
Creating a Database
Firstly let create a database using MySQL Command Line Client console. We
cannot find how to create a MySQL database using NetBeans. However there
are wizard to create Java database for Derby database. After finishing the
database creation, exit and open NetBeans.
SQL statement to create database is:
Well, NetBeans 6.0 provides drivers for JDBC-ODBC (Windows driver for
Microsoft Access/MSSQL), MySQL, Java and PostgreSQL database. This
means that no need for us to install third party driver for these databases as
version 5.5. Thanks to NetBEans and in the future there will be more drivers for
other dominant databases used in the market such as Oracle, Sybase etc. A new
driver can be added to NetBeans using the following steps.
And fill in the needed information in the following Figure. Get the third party
JDBC driver for various databases at sun.com.
Next, select MySQL (Connector/J driver) and right-click mouse button. Select
Connect Using… context menu.
The New Database Connection wizard launched. Use the following connection
string. Key in the MySQL username as root and its password that you use to
access your MySQL database.
jdbc:mysql://localhost:3306/tid5013studentrecord
The format for the connection string for this driver is:
jdbc:mysql://<hostname>:<database_access_port_number>/
<database_name>
Using root user is not a good practice. We need to create MySQL users and
assign appropriate level of permissions and rights to those users and use them in
different level of database accesses such as users for update, backup and many
more. Left the root as the highest administrator similar to Windows
(Administrator) and Linux (root) system access. Click the Remember password
tick box if you want the password to be remembered so next time no need to key-
in the password any more. Click OK.
If your connection is successful it will be notified (Connection established) in
the following frame and same as if it is fail. Click the OK button.
Now we are connected to the MySQL database through NetBeans. You can see
icon for the established connection as shown below.
Creating a Table
Next step is to create table and then populate it with sample data. The following
table describes our sample table structure. (The red record has some issue to be
resolved later. There are some incompatibilities between java.util.date and
java.sql.date here. Quick solution is to use int or String type for the
stud_date_of_birth or we can separate the year, month and day into different
fields/columns).
And the following is the SQL script for our table creation.
To execute this SQL script, select the previously established connection (our
MySQL database), right-click mouse and select Execute Command… context
menu.
Type or copy-paste the SQL script into the SQL Command editor as shown
below. Make sure you have chosen a proper database as blue highlighted in the
Connection: field
DESC studentrecord;
The following figure shows that our table has been successfully created.
Congrats!!!
Use the following sample SQL scrip to insert sample data into out table. You can
try creating your own sample data. Launch and use new SQL Command editor
or you can overwrite the previous SQL script. Execute/run the script as done
previously.
'88799','Mustar','Mohd Dali','1979-06-24',
'345, Side Village, Kerian, 12300 Jawa Barat','MSc.
MultiMedia',
'1','Indonesia');
Any success or fail will be notified in the Output window at the bottom of the
NetBeans IDE. So don’t worry. A screen snapshot is shown below. Notice the
different default colors used in the SQL script. Keywords, values and table name
are in different colors and together with the report in the Output window, this
makes our tasks in troubleshooting easier.
Verify our data/values insertion by using the following SQL statement.
-- create a table
student_id VARCHAR(7),
) ENGINE=innodb;
'88889','Albukori','Zaman Khan','1969-07-08',
'1','Malaysia');
'87990','Haslina','Mahathir','1970-11-12',
'2','Malaysia');
INSERT INTO studentrecord VALUES(
'79678','Mohammed','Fajr','1975-04-20',
'2','UEA');
'88799','Mustar','Mohd Dali','1979-06-24',
'1','Indonesia');
'78998','Satkorn','Chengmo','1968-01-26',
'2','Thailand');
Next step is to create a GUI for our database access and manipulation. The
following screen snapshots are self-explanatory.
Creating a New Java Desktop Project
Next let see our real GUI in action. You can build first and then run. In this case
we directly run the project (in the process it will be built as other Java project).
Select the StudentRecordApp project folder, right-click mouse and select Run
menu.
Here is the Real GUI. Try the File menu and its sub-menu. In this case not all the
record was displayed. Only the first three and this is our job to find the cause and
it is a normal process in programming! Select any record and test the New (click
New button and key-in new data and click Save to update new data), Delete
(select a record to be deleted and press the Delete button) and Refresh (refresh
the connection and update the data) buttons. All controls supposed to be working
else we need to find the reasons and resolve it.
Customizing the GUI
Close this application. Let go back to the design page. Select the Stud Date Of
Birth text field. Go to the Properties sheet and click the Binding.
Click the ellipses (…) at the end of the text field.
Try selecting the date int type in the Binding Expression: field, expand the
studDateOfBirth java.util.Date and select date int and then click OK.
Re-run the Project and Testing Its Functionality
If we want to add other component either to bind to the database table or not it is
depend on our creativities now.
Re-run this project again and see the result!
Regarding the Date Of Birth (DOB), well we think here is the reason. Searching
in the Internet, the reason is the java.util.Date is not compatible with the
java.sql.Date. Older java.util.Date package that contains date only already
deprecated. The new version of this java.util.date contains date and time as
well, while the java.sql.util only contains the date. Coding wise, we need to
parse or convert to the java.sql.Date format. The validation and conversion
features already available in the Java Server Faces (JSF) web development.
As said before we can fix this problem immediately. Easy solution is to use a
String type for the stud_date_of_birth replacing the DATE data type. From this
simple issue, that is why the database design stage is very important.
The structure for a studentrecord table
Column name Data type Constraint
s
student_id VARCHAR(7) NOT NULL
PRIMARY
KEY
stud_first_name VARCHAR(15 NOT NULL
)
stud_last_name VARCHAR(15 NOT NULL
)
stud_date_of_birth VARCHAR(10 NOT NULL
)
stud_address VARCHAR(50 NOT NULL
)
stud_program VARCHAR(20 NOT NULL
)
stud_marital_statu INT(2) NOT NULL
s
stud_country VARCHAR(20 NOT NULL
)
Or we can separate the year, month and day into different fields/columns. (We
have tried this, also failed).
… … …
stud_last_na VARCHAR(1 NOT
me 5) NUL
L
stud_dob_day INT(2) NOT
NUL
L
stud_dob_mo INT(2) NOT
nth NUL
L
stud_dob_yea INT(4) NOT
r NUL
L
stud_address VARCHAR(5 NOT
0) NUL
L
… … …
And for this case we need to create (I mean, NetBeans create for us and we re-
arrange it in the frame) different fields for each column and we need to re-
arrange the day, month and year in the standard format in the GUI such as:
In this tutorial we will continue customizing our Java desktop GUI and MySQL
database project. The original tutorial can be found at netbeans.org. All credits
must go to the original authors.
The following is the Java desktop GUI from the previous tutorial and we faced a
problem regarding the Stud Date Of Birth that was not properly displayed, only
the day was displayed. We will resolve this later.
In this tutorial we will continue customizing our Java desktop GUI and MySQL
database project. The original tutorial can be found at netbeans.org. All credits
must go to the original authors.
The following is the Java desktop GUI from the previous tutorial and we faced a
problem regarding the Stud Date Of Birth that was not properly displayed, only
the day was displayed. We will resolve this later.
Some Notes on Java GUI from the Plain Old Java Code View
Other than command-line applications which interact with the user only through
simple text prompts, Java application can have graphical components as well.
You should be familiar with the graphics and images displayed inside web
pages that use Java applets. Java applets are a Java program that is intended
to be embedded in a web page and executed through a browser.
Java also has capabilities to create programs with graphical user interfaces
(GUIs). A GUI component is an object that represents a screen element that is
used to display information or to allow the user to interact with the program in a
certain way. GUI components include labels, buttons, text fields, scroll bars,
menus and many more.
Java components and other GUI-related classes are defined primarily in two
packages: java.awt and javax.swing. The Abstract Windowing Toolkit (AWT)
was the original Java GUI package. It still contains many important classes
such as the Color class.
The swing package was added later and provides components that are more
versatile than those of the AWT package. Both packages are needed for GUI
development, but we should use Swing components whenever there is an
option.
Containers are generally not useful unless they help us organized and display
other components. For example, a label is a component that displays a line of
text in a GUI. A label can also display an image as well. Usually, labels are used
to display information or identify other components in the GUI. Labels can be
found in almost every GUI-based program.
The following program example tries to demonstrate the basic use of frames,
panels and labels.
import java.awt.*;
import javax.swing.*;
primary.add(label1);
primary.add(label2);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
}
A sample output:
When this program is executed, a new window appears on the screen displaying
a phrase. The text of the phrase is displayed using two label components. The
labels are organized in a panel and the panel is displayed in the content pane of
the frame.
The JFrame constructor takes a string as a parameter, which it displays in the
title bar of the frame. The call to the setDefaultCloseOperation() method
determines what will happen when the close button (X) in the top-right corner is
clicked. In most cases we will simply let that button terminate the program, as
indicated by the EXIT_ON_CLOSE constant.
A panel is created by instantiating the JPanel class. The background color of the
panel is set using the setBackground() method. The setPreferredSize() method
accepts a dimension object as a parameter, which is used to indicate the width
and height of the component in pixels. The size of many components can be set
this way and most components also have setMinimumSize() and
setMaximumSize() methods to help control the look of the interface.
The labels are created by instantiating the Jlabel class, passing to its constructor
the text of the label. In this program two separate label components are created.
Finally, the content pane of the frame is obtained using the getContentPane()
method, immediately after which the add method of the content pane is called to
add the panel. The pack method of the frame sets its size appropriately based on
its contents; in this case the frame is sized to accommodate the size of the panel
it contains. This is a better approach than trying to set the size of the frame
explicitly, which should change as the components within the frame change. The
call to the setVisible() method causes the frame to be displayed on the monitor
screen.
Let forget the Java old plain code in building the Java GUI. Let continue our task
using NetBeans, the Java IDE that automate most of the works that previously
need to be done manually. For our project, the following is the MainPanel
container that together with other containers fitted in the main Frame.
The following is the MenuBar container.
The following is the StatusPanel container.
1. Next we also would like to remove the Stud word for the table column
headers. Select the table panel > right click mouse > select Table Contents
context menu.
2. Select Columns tab > select the second row > click the ellipses at the end of
the Title: text field.
3. In the text area removes the Stud, leaving the First Name. Don’t forget to
remove the Define as a Resource tick and click OK. We faced some
problems when selecting the Define as a Resource which the changes that
have been set do not take effect. Repeat these steps for other remaining
columns except the Student Id.
4. The following Figure shows our current Java GUI when built and run.
5. Next, we remove the table grid color to white, that means there is no grid in
the table. Select the table > right click mouse > select Properties context
menu.
6. In gridColor property, change the color to white. Click the ellipses to choose
the white color.
7. Next, let re-build our Java desktop GUI application. As usual select the
project node > right click mouse > select Build context menu.
8. Notice the progress in the Output window. Make sure there is no error.
9. Then, re-run the project. Select the project node > right click mouse > select
Run context menu.
10. The following Figure show the Java GUI when in running mode. Then the
table doesn’t have a grid anymore. Notice that all the table columns headers
changed to First Name! You need to change back all the headers to their
respective name as described in the previous steps. This is bug or what, we
don’t know.
11. The following is the same data seen through the SQL query. It is confirm that
the table column headers don’t changed as expected.
MySQL Database and Java Desktop GUI Part 3
Contents:
1. Adding a Print Table Feature
2. Adding the Print Table Code
3. Customizing the Menu Items
4. Solving the Date Of Birth Issue: Editing the Table
5. Adding Static Text and Image
6. Adding Panel, Labels, Static Text And Image
7. Adding radio button
8. Running and Testing
9. Customizing the Frame and the About Page.
10. Final Note
In this tutorial we continue playing with NetBeans and Java desktop GUI project,
continue to customize our GUI by setting up the table printing, adding menu
items, image, static text, button, panel, codes for event handling and so on. On
the way we will try to solve the DOB issue which we will change the data type
from DATE to VARCHAR. Appreciate the steps on how to edit the original table
properties while designing the GUI interface. Our main purpose actually to be
familiar with the NetBeans IDE features.
1. Let do it. Firstly we would like to add a Print button to print a table. Drag and
drop the jButton on the design canvas on the right most, above the table.
2. Select the button > click Properties context menu.
3. Change the mnemonic, text and ToolTipText as shown in the following
Figure. Click Close.
4. The current GUI is as shown in the following Figure as seen in preview
mode.
5. Next we re-position all the buttons at the top, inline with the Print button just
above the table and re-arranged other components, leaving the top area an
empty space for other components that will be added later. This is a drag and
drop task.
6. Next we would like to add the event handler to the Print button, which means
action to done when the button clicked event happened. Select the Print
button > right click mouse > select Event > select Action > select
actionPerformed.
2. Add the following import directives for the classes (methods) that we need to
use in the StudentRecordView.java file.
import java.text.MessageFormat;
import java.awt.print.*;
import javax.swing.JTable;
3. Add the following code for the jButton1ActionPerformed() event handler. We
are using the JTable to print only the table.
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
MessageFormat header = new MessageFormat("Page
{0,number,integer}");
MessageFormat footer = new MessageFormat("TID
5013 Assignment #1");
try {
//table.print(JTable.PrintMode.FIT_WIDTH,
header, null);
masterTable.print(JTable.PrintMode.FIT_WIDTH, header,
footer);
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n",
e.getMessage());
}
}
4. Actually, you can try completing the code first instead of adding the import
directives and then use the Fix Imports context menu as shown in the
following Figure. We will use this feature frequently in the Java web project.
5. Next, add the Print menu by using menu Item component.
6. Drag and drop the Menu Item component between the Refresh and Exit
menu items.
5. Next we add a separator between the Refresh and the Print menu items.
6. Drag and drop a separator between Refresh and Print men items.
7. Assign an event handler when user clicks the Print menu by invoking the
Events > Action > actionPerformed.
masterTable.print(JTable.PrintMode.FIT_WIDTH, header,
footer);
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n",
e.getMessage());
}
10. Re-build and re-run the project. Select the Print sub menu under the File
menu, see the effect.
11. The following message box displayed when there is no printer driver (spooler
service) installed.
12. Don’t forget also to test the Print button. The following Figure shows the print
dialog box. In this case we would like to print the table to PDF file. All printers
that available in the machine where this program run will be displayed in the
Name: drop down list. Click the Print button.
1. Select the database in the Schemata windows > right click mouse > select
make Default Schema, to make it a current schema.
7. Next, bind to the Master Table data. Select the DOB text field > right click
mouse > select Bind > select text.
8. Select dateOfBirth java.lang.String for the Binding Expression and click OK.
9. Next, add the DOB field/column into the table. Select table > right click
mouse > click Table Contents context menu.
10. Click the Columns tab.
11. Click the Insert button and select the newly added row.
12. Change the Title: and Expression: as shown in the following Figure.
13. Use the Move Up button to move the DOB row between Name and Address
and click Close.
14. The Date Of Birth was added to the table as shown in the following Figure.
Adding Static Text and Image
For this task you need to have an image. This image and other project resources
such as icon need to be saved under the project’s resources folder. In this case,
the image file name is uum.png and shown below. You can use other image if
you want.
1. Next we drag and drop a JPanel (1) at the top of the main panel and below
the JMenuBar. In the panel we drag and drop three labels, one for logo image
(2) and another two for the static texts (3 and 4).
2. To load the image, use the icon property of the Jlabel (2) in Properties page.
Any image that saved under the resources folder will be visible in the drop
down list.
6. We continue customizing the look and feel such as colour, border, text etc.
for the existing components. This steps just to practise what we have done
previously.
1. Drag and drop two radio buttons on the right side of the Marital Status’s text
field so that when user select a radio button, the value of 0 or 1 will be
displayed in the Marital Status’s text field.
2. Change the text labels as shown below.
3. We need to group these radio buttons so that at any time only one radio
button will be selected. Drag and drop the Button Group component on the
panel. You can’t see it in the panel but available in the Inspector window.
4. Multiple select the radio buttons (press down Ctrl button and multiple select
those radio buttons).
This has been tried and it was successful. So we can distribute the
uumstudentrecordUI.jar as the executable (Java bytecode).
3. Invoking the printing feature. Click the Print button or Print sub menu.
Customizing the Frame and the About Page.
2. In our case we edit the keys to the following values (leave the
Application.name key). Edit the keys’ values to suit your application
accordingly. Click the cell in the Value column and edit the text as needed.
3. Run your project and invoke the About sub menu. Notice that the frame’s title
also changed.
4. Next, we are going to customize the image in the About page. In this case we
use Adobe Photoshop CS3. You can use other image editors as well.
5. Open the original image, about.png under the resources folder in the
Photoshop (or any image editor). You can also create your own image from
scratch. The splash.png image will be used for installation/deployment.
6. We edit the original image to the following colors and save to its original file
name (overwrite).
7. Run our project and invoke the About sub menu. The new image was
displayed as shown below.