Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
71 views

MySQL Database and Java Desktop GUI

oop

Uploaded by

aliza
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

MySQL Database and Java Desktop GUI

oop

Uploaded by

aliza
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 110

MySQL Database and Java Desktop GUI Part 1

http://www.javaguicodexample.com/javadesktopguidatabaseappsdev.html

1. Machine specification used for this task


2. Pre-requirement
3. Creating a Database
4. Making a Connection to a Database
5. Creating a Table
6. Inserting a Sample Data
7. Creating a New Java Desktop Project
8. Running the Project for the First Time
9. Customizing the GUI
10. Re-run the Project and Testing Its Functionality

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.

Machine specification used for this task

 Intel Pentium Core 2 Duo, 2.2 GHz,


 Windows XP Pro SP2 + periodical patches + periodical updates.
 2 GB DDR2 RAM
 160 GB SATA HDD
 17” SyncMaster 713N monitor.

Pre-requirement: NetBeans 6.x.x and MySQL 5.x.x

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:

CREATE DATABASE tid5013studentrecord;

Change the database name accordingly if you want.


When the NetBeans IDE launched, go to the Services pane, expand the
Databases folder and expand the Drivers sub-folder.
Making a Connection to a Database

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>

Change the database name accordingly if needed. Click the OK button.

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).

The structure for a studentrecord table


Column name Data type Constrain
ts
student_id VARCHAR(7 NOT NULL
) PRIMARY
KEY
stud_first_name VARCHAR(1 NOT NULL
5)
stud_last_name VARCHAR(1 NOT NULL
5)
stud_date_of_bir DATE NOT NULL
th
stud_address VARCHAR(5 NOT NULL
0)
stud_program VARCHAR(2 NOT NULL
0)
stud_marital_sta INT(2) NOT NULL
tus
stud_country VARCHAR(2 NOT NULL
0)

And the following is the SQL script for our table creation.

CREATE TABLE IF NOT EXISTS studentrecord (


student_id VARCHAR(7),
stud_first_name VARCHAR(15) NOT NULL,
stud_last_name VARCHAR(15) NOT NULL,
stud_date_of_birth DATE NOT NULL,
stud_address VARCHAR(50) NOT NULL,
stud_program VARCHAR(20) NOT NULL,
stud_marital_status INT(2) NOT NULL,
stud_country VARCHAR(20) NOT NULL,
PRIMARY KEY (student_id)
) ENGINE=innodb;

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

Then, run/execute the script by clicking the run/execute icon.


Verify the studentrecord database creation by using the following command in
new SQL Command editor. You can also combine and execute/run this code
together with the previous SQL script.

DESC studentrecord;

The following figure shows that our table has been successfully created.
Congrats!!!

Next step is to populate the studentrecord with sample data.


Inserting a Sample Data

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.

INSERT INTO studentrecord VALUES(


'88889','Albukori','Zaman Khan','1969-07-08',
'4-5, Dead Wood Street 5, 12000 Sintok, Kedah','MSc. IT',
'1','Malaysia');

INSERT INTO studentrecord


VALUES('87990','Haslina','Mahathir','1970-11-12','345, New
Smart Village, 17100 Nilai, N. Sembilan','MSc.
ICT','2','Malaysia');

INSERT INTO studentrecord VALUES(


'79678','Mohammed','Fajr','1975-04-20',
'Pearl Apt, Level 10, Al-Hijr, 45200 Abu Dhabi','MSc. Expert
System',
'2','UEA');

INSERT INTO studentrecord VALUES(

'88799','Mustar','Mohd Dali','1979-06-24',
'345, Side Village, Kerian, 12300 Jawa Barat','MSc.
MultiMedia',
'1','Indonesia');

INSERT INTO studentrecord VALUES(


'78998','Satkorn','Chengmo','1968-01-26',
'34 Uptown Street #4, Tech Park, 78100 Bangkok','MSc. IT',
'2','Thailand');

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.

SELECT * FROM studentrecord;


A complete MySQL script for this exercise is given below.

-- create a table

CREATE TABLE IF NOT EXISTS studentrecord (

student_id VARCHAR(7),

stud_first_name VARCHAR(15) NOT NULL,

stud_last_name VARCHAR(15) NOT NULL,

stud_date_of_birth DATE NOT NULL,

stud_address VARCHAR(50) NOT NULL,

stud_program VARCHAR(20) NOT NULL,

stud_marital_status INT(2) NOT NULL,

stud_country VARCHAR(20) NOT NULL,

PRIMARY KEY (student_id)

) ENGINE=innodb;

-- insert a sample data

INSERT INTO studentrecord VALUES(

'88889','Albukori','Zaman Khan','1969-07-08',

'4-5, Dead Wood Street 5, 12000 Sintok, Kedah','MSc. IT',

'1','Malaysia');

INSERT INTO studentrecord VALUES(

'87990','Haslina','Mahathir','1970-11-12',

'345, New Smart Village, 17100 Nilai, N. Sembilan','MSc.


ICT',

'2','Malaysia');
INSERT INTO studentrecord VALUES(

'79678','Mohammed','Fajr','1975-04-20',

'Pearl Apt, Level 10, Al-Hijr, 45200 Abu Dhabi','MSc. Expert


System',

'2','UEA');

INSERT INTO studentrecord VALUES(

'88799','Mustar','Mohd Dali','1979-06-24',

'345, Side Village, Kerian, 12300 Jawa Barat','MSc.


MultiMedia',

'1','Indonesia');

INSERT INTO studentrecord VALUES(

'78998','Satkorn','Chengmo','1968-01-26',

'34 Uptown Street #4, Tech Park, 78100 Bangkok','MSc. IT',

'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

Well, click File > select New Project.


Select Java in the Categories: and Java Desktop Application in the Projects:
pane. Click Next.
Put the project name as StudentRecordApp and change the location if needed
else just leave as it is. Select the Database Application in the Choose
Application Shell pane. Click Next.
Select our previously created database connection in the Database Connection
text field. We only have one table here, so no need to select any as shown in the
Database Table: field. In this case we include all the table columns. You can
exclude some columns if needed. Click Next button.
By default the first radio button has been selected. Just leave as it is. Click
Finish button and wait.
Here you are! Our database GUI template! This GUI can be built and
run/executed as other Java project.
You can view the GUI by clicking the Preview Design icon ( ).
Running the Project for the First Time

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

Re-run this project again.


Select any row of the table. All the record displayed but the Stud Date Of Birth
just display the day only. However this program can be said 97% working.

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:

MySQL Database and Java Desktop GUI Part 2


Contents:
1. Some Notes on Java GUI from the Plain Old Java Code View
2. Java GUI: Components and Containers
3. Frames and Panels
4. Customizing the Java GUI
5. Customizing the Table Layout

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

Java GUI: Components And Containers

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.

A container is a special type of component that is used to hold and organize


other components. Frames and panels are two examples of Java containers.
Frames and Panels

A frame is a container that is used to display GUI-based Java applications. A


frame is displayed as a separate window with its own title bar. It can be
repositioned on the screen and resized as needed by dragging it with the
mouse. It contains a standard small buttons in the corner of the frame that allow
the frame to be minimized, maximized and closed. A frame is defined by the
JFrame class.

A panel is also a container. However, unlike a frame, it cannot be displayed on


its own. A panel must be added to another container for it to be displayed.
Generally a panel doesn’t move unless you move the container that it is in. Its
primary role is to help organize the other components in a GUI. A panel is
defined by the JPanel class.

We can classify containers as either heavyweight or lightweight. A heavyweight


container is one that is managed by the underlying operating system on which
the program is run, whereas a lightweight container is managed by the Java
program itself. Occasionally this distinction will be important when we explore
GUI development. A frame is a heavyweight component and a panel is a
lightweight component.

Heavyweight components are complex that lightweight components in general.


A frame, for example has multiple panes, which are responsible for various
characteristics of the frame window. All visible elements of a Java interface are
displayed in a frame’s content pane.

Generally, we can create a Java GUI-based application by creating a frame in


which the program interface is displayed. The interface is often organized onto a
primary panel which is added to the frame’s content pane. The components in
the primary panel are often organized using other panels as needed.

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.*;

public class Framepanellabel


{
public static void main(String[] args)
{
JFrame frame = new JFrame ("Java GUI Components");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS
E);

JPanel primary = new JPanel();


primary.setBackground (Color.yellow);
primary.setPreferredSize(new Dimension(250,75));

JLabel label1 = new JLabel("Java GUI components,


");
JLabel label2 = new JLabel ("Frame, panel and
label.");

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.

Containers have an add() method that allows other components to be added to


them. Both labels are added to the primary panel and from that point on
considered to be part of that panel. The order in which components are added to
a container often matters. In this case, it determines which label appears above
the other.

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.

Customizing the Java GUI

1. Next we would try to customize GUI components in our project. Firstly, we


re-position the table at the bottom of the frame by click-drag and drop.
2. Next, delete the Date of birth label and its text field. We will customize this
component later. Select the Date of Birth component > right click mouse >
select Delete context menu.
3. Then re-arrange other controls. We re-position the buttons at the top. Click-
hold-drag and drop those buttons.
4. Re-position all the components by dragging and dropping.
5. Next we resize the text fields. This is a drag and resize task.
6. Next, we change the Save button text to Update. Select the Save button >
right click mouse > select Properties context menu.
7. In the text property, change to Update and change also the mnemonic
property to U.
8. Next we change the background for the text fields to white. Select the text
field > go to Properties page > click the ellipses at the end of the background
property.
9. Select the Swatches tab and select the white color. Click OK.
10. The following Figure shows our current Java GUI.
11. Next we edit the labels by removing the Stud word for all labels except
Student Id. Click the label, wait for a while, click again and edit.
Customizing the Table Layout

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.

Adding a Print Table Feature

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.

Adding the Print Table Code

1. NetBeans provide us the method skeleton as shown in the following Figures.


This is the StudentRecordView.java file.

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.

7. Customize the new menu item through the Properties page.


Customizing the Menu Items
1. Use the following information for the menu item.
1. mnemonic: P
2. text: Print
3. accelerator: Ctrl + P (click the ellipses)
2. Repeat the same steps for other menu items. The following is for the Delete
menu item.

3. Next, for the New menu item


4. The final menu items are shown below.

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.

8. The following is the location of the jMenuItemActionPerformed() event


handler skeleton provided for us that ready for our customized codes.
9. Add the following codes manually.

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());
}

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.

13. Put the file name and click Save.


14. The following is a sample of the table printed to the PDF file.

Solving the Date Of Birth Issue: Editing the Table


Previously we have some problem in displaying the Date Of Birth (DOB). Keep in
mind that the DOB field and data still available in the table. We use the DATE
data type for this field. Now we would like to change the data type to VARCHAR
and re-include the field in our Java desktop GUI.
First of all we need to edit the DOB data type using MySQL Query Browser.
Launch MySQL Query Browser.

1. Select the database in the Schemata windows > right click mouse > select
make Default Schema, to make it a current schema.

2. The database node will be in bold.


3. Next, select the table > right click mouse > select Edit Table context menu.

4. Click the DATE for the date_of_birth and change it to VARCHAR(15).


5. Click the Apply Changes button. Click Execute for the Table Edit
confirmation dialog box. Close MySQL Query Browser.
6. Next, re-include the DOB field in the Java GUI. Add Label and text field to the
GUI and put them between the Name and Address fields.

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.

15. We save the image under the project’s resources folder.


16. Then we can see it through the Project window under the
project_name.resources (in this case it is
uumstudentrecordui.resources) folder as shown below. When you
double click the image file, it will be displayed on the right window.

Adding Panel, Labels, Static Text And Image

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.

3. For the no. 3 label, we customize the font, foreground, horizontalAlignment


and text properties. Customize them to your needs.
4. For no. 4 label, we customize background, font, foreground,
horizontalAlignment, text, ToolTipText and we select the opaque properties.
5. Our final appearance will look something like the following. You can change it
to suit your application needs.

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.

Adding Radio Button

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).

5. Go to the Properties sheet and set the buttonGroup property to


buttonGroup1. For only two radio buttons, there is no extra code to be added.
If more than two radio buttons, we need to do some coding in order to match
or select appropriate values.
6. Bind the radio buttons to the Marital Status master table column. Select the
first radio button and right-click mouse. Select Bind > select selected.

7. Select maritalStatus int in the Binding Expression field. Click OK.


Running and Testing

1. Build, run and test your radio button.


2. To run this application from the command line without Ant, try:

java -jar "C:\myjavaproject\uumstudentrecordUI\dist\


uumstudentrecordUI.jar"

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.

1. Expand the project_name.resources subfolder under the Source


Packages folder. Select and right-click the project’s application properties
link and choose the Open context menu.

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.

You might also like