Chapter Five
Graphical User Interface and Java Database connectivity
Creating Graphical User Interface (GUI) using NetBeans IDE
This chapter introduces Graphical User Interface (GUI) programming in java with Swing components
(Textfield, buttons, Labels, check box, etc) using NetBeans IDE. The NetBeans IDE is a free, open-
source, cross-platform integrated development environment with built-in support for Java
programming language.
The goal of this lesson is to introduce the Swing API (Application program Interface) by designing a
simple application that accept values from one textfield and display in second textfield. Its GUI will be
basic, focusing on only a subset of the available Swing components. We will use the NetBeans IDE
GUI builder, which makes user interface creation a simple matter of drag and drop. Its automatic code
generation feature simplifies the GUI development process, letting you focus on the application logic
instead the underlying infrastructure.
Because this lesson is a step-by-step checklist of specific actions to take, we recommend that you run
the NetBeans IDE and perform each step as you read along. This will be the quickest and easiest way
to begin programming with Swing.
Add Jframe form in your project and drag and drop four textfields, four labels and two buttons. Let
the name of four textfields are txt1, txt2, txt3 and txt4. Let also the caption of the labels are String
Input , Number Input ,Value 1 and Value 2. Let also the name of buttons are btndisplay and btnclear.
Make the caption of the two buttons as Display and Clear as shown below.
To give caption/label right click on the button or label or text field and select Edit Text.
To give name right click on textfield or button or label and select Change Variable Name.
1
Data validations for txt1 and txt2 textfield
Let txt1 must accept only letters and txt2 accept only numbers (0-9). Use the following codes to do
these validations.
//import [Link]; at the top of the class
//Letter validation,Right click on txt1,then point to Events then point to Key finally select KeyPessed
private void txt1KeyPressed([Link] evt) {
if( ([Link]() >= 'a' && [Link]() <= 'z')||([Link]() >= 'A' && [Link]() <= 'Z'))
[Link](true);
else {
[Link](false);
[Link](null," please enter only letter");
[Link](true);
}
}
//Number validation
private void txt2KeyPressed([Link] evt) {
if ([Link]() >= '0' && [Link]() <= '9')
[Link](true);
else {
[Link](false);
[Link](null," please enter only numeric digits(0-9)");
[Link](true);
}
}
//Code for btndisplay button
// Right click on btndisplay and point to Events then point to Action and then Actionperformed
private void btndisplayActionPerformed([Link] evt)
2
{
String s1=[Link]();
[Link](s1);
String s2=[Link]();
[Link](s2);
}
private void btnclearActionPerformed([Link] evt)
{
[Link](“ ”);
[Link](“ “);
[Link](“ “);
[Link](“ “);
}
Second Example: GUI Calculator
Design the following form and write for +,-,*,/,%,= and clear buttons action performed event. Write
also action performed event code for 0,1,2,3,4,5,6,7,8,9 and .(dot) buttons.
The operators +,-,*,/,% shoud be set at operator textfield and 1,2,3,4,5,6,7,8,9,0 and . should be set at
Num1 or Num2 textfield.Num1 textfield should be filled first and then the operator textfield and
finally the Num2 textfield.
//code for each button
private void btn1ActionPerformed([Link] evt)
{
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
3
} else
{ str= [Link]() + [Link]();
[Link](str);
}
}
private void btn2ActionPerformed([Link] evt)
{
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
} else
{ str= [Link]() + [Link]();
[Link](str);
}
}
private void btn3ActionPerformed([Link] evt)
{
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
} else
{ str= [Link]() + [Link]();
[Link](str);
}
}
private void btn4ActionPerformed([Link] evt)
{
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
} else
{ str= [Link]() + [Link]();
[Link](str);
}
}
private void btn5ActionPerformed([Link] evt)
{
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
} else
{ str= [Link]() + [Link]();
[Link](str);
}
4
}
private void btn6ActionPerformed([Link] evt)
{
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
} else
{ str= [Link]() + [Link]();
[Link](str);
}
}
private void btn7ActionPerformed([Link] evt)
{
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
} else
{ str= [Link]() + [Link]();
[Link](str);
}
}
private void btn8ActionPerformed([Link] evt)
{
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
} else
{ str= [Link]() + [Link]();
[Link](str);
}
}
private void btn9ActionPerformed([Link] evt)
{
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
} else
{ str= [Link]() + [Link]();
[Link](str);
}
}
private void btn0ActionPerformed([Link] evt)
{
5
String str=null;
if([Link]().equals(""))
{ str = [Link]() + [Link]();
[Link](str);
} else
{ str= [Link]() + [Link]();
[Link](str);
}
}
private void btndotActionPerformed([Link] evt)
{
String str;
if([Link]().equals(""))
{
str = [Link]() + [Link]();
[Link](str);
[Link](false);
}
else
{
str = [Link]() + [Link]();
[Link](str);
[Link](false);
}
private void btnaddActionPerformed([Link] evt)
{
if([Link]().equals(""))[Link](null," Enter value in the first
textfield");
else{
[Link]("+");
[Link](true);
}
}
private void btnsubtActionPerformed([Link] evt)
{
if([Link]().equals(""))[Link](null," Enter value in the first
textfield");
else{
[Link]("-");
6
[Link](true);
}
private void btnmultActionPerformed([Link] evt) {
if([Link]().equals(""))[Link](null," Enter value in the first
textfield");
else{
[Link]("*");
[Link](true);
}
}
private void btndivActionPerformed([Link] evt)
{
if([Link]().equals(""))[Link](null," Enter value in the first
textfield");
else{
[Link]("/");
[Link](true);
}
}
private void btnmodActionPerformed([Link] evt)
{
if([Link]().equals(""))[Link](null," Enter value in the first
textfield");
else{
[Link]("%");
[Link](true);
}
}
private void btnequalActionPerformed([Link] evt) {
float val1=[Link]([Link]());
float val2= [Link]([Link]());
String oper=[Link]();
String result=null;
if([Link]("+"))
{ result= val1+val2;
[Link]([Link](result));
}
else if([Link]("-"))
7
{ result= val1-val2;
[Link]([Link](result));
}
else if([Link]("*"))
{ result= val1*val2;
[Link]([Link](result));
}
else if([Link]("/"))
{ if(val2==0) [Link](null," Division by zero is not allowed");
else{
result= val1/val2;
[Link]([Link](result));
}
}
else if([Link]("%"))
{ result= val1%val2;
[Link]([Link](result));
}
}
private void btnclearActionPerformed([Link] evt) {
[Link]("");
[Link]("");
[Link]("");
[Link]("");
[Link](true);
}
Java Database Connectivity(JDBC)
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API (Application Program
Interface) for database-independent connectivity between the Java programming language and a wide
range of databases.
The JDBC library includes APIs for each of the tasks commonly associated with database usage:
Making a connection to a database
Creating SQL or MySQL statements
Executing that SQL or MySQL queries in the database
Viewing & Modifying the resulting records
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables,
such as:
8
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
All of these different executables are able to use a JDBC driver to access a database and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in
general JDBC Architecture consists of two layers:
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity
to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The driver
manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous
databases.
Following is the architectural diagram, which shows the location of the driver manager with respect to
the JDBC drivers and the Java application:
9
Common JDBC Components:
The JDBC API provides the following interfaces and classes:
DriverManager: This class manages a list of database drivers. Matches connection requests
from the java application with the proper database driver using communication subprotocol.
Driver: This interface handles the communications with the database server.
Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection
object only.
Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.
ResultSet: These objects hold data retrieved from a database after you execute SQL query
using Statement objects. It acts as temporary table that allow you to move through its data.
SQLException: This class handles any errors that occur in a database application.
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database
server.
10
For example, using JDBC drivers enable you to open database connections and to interact with it by
sending SQL or database commands then receiving results with Java.
The [Link] package that ships with JDK contains various classes with their behaviors defined and
their actual implementations are done in third-party drivers. Third party vendors implement the
[Link] interface in their database driver.
JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of operating systems and hardware
platforms in which Java operates. Sun has divided the implementation types into four categories,
Types 1, 2, 3, and 4, which are explained below:
Type 1: JDBC-ODBC Bridge Driver:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine.
Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the
target database.
When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
11
Type 2: JDBC-Native API:
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the
database. These drivers typically provided by the database vendors and used in the same manner as the
JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.
If we change the Database we have to change the native API as it is specific to a database and they are
mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it
eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3: JDBC-Net pure Java:
In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard
network sockets to communicate with a middleware application server. The socket information is then
translated by the middleware application server into the call format required by the DBMS, and
forwarded to the database server.
12
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client
application. As a result, you need some knowledge of the application server's configuration in order to
effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
Type 4: 100% pure Java:
A Type 4 driver is a pure Java-based driver that communicates directly with vendor's database through
socket connection. This is the highest performance driver available for the database and is usually
provided by the vendor itself.
This kind of driver is extremely flexible; you don't need to install special software on the client or
server. Further, these drivers can be downloaded dynamically.
13
Oracle thin driver and MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary
nature of their network protocols, database vendors usually supply type 4 drivers.
JDBC Database Connections
After you've installed the appropriate driver, it's time to establish a database connection using JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are these simple four
steps:
Import JDBC Packages: Add import statements to your Java program to import required
classes in your Java code.
Register JDBC Driver: This step causes the JVM to load the desired driver implementation
into memory so it can fulfill your JDBC requests.
Database URL Formulation: This is to create a properly formatted address that points to the
database to which you wish to connect.
Create Connection Object: Finally, code a call to the DriverManager object's getConnection(
) method to establish actual database connection.
Import JDBC Packages:
The Import statements tell the Java compiler where to find the classes you reference in your code and
are placed at the very beginning of your source code.
14
To use the standard JDBC package, which allows you to select, insert, update, and delete data in SQL
tables, add the following imports to your source code:
import [Link].* ; // for standard JDBC programs
import [Link].* ; // for BigDecimal and BigInteger support
Register JDBC Driver:
You must register your driver in your program before you use it. Registering the driver is the process
by which the Oracle driver's class file is loaded into memory so it can be utilized as an implementation
of the JDBC interfaces.
You need to do this registration only once in your program.
You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as the
one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver:
try {
Driver myDriver = new [Link]();
[Link]( myDriver );
}
catch(ClassNotFoundException ex) {
[Link]("Error: unable to load driver class!");
[Link](1);
}
Database URL Formulation:
After you've loaded the driver, you can establish a connection using the
[Link]() method.
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your database.
Formulating a database URL is where most of the problems associated with establishing a connection
occur.
Following table lists down popular JDBC driver names and database URL.
RDBMS JDBC driver name URL format
MySQL [Link] jdbc:mysql://hostname:port Number/ databaseName
15
ORACLE [Link] jdbc:oracle:thin:@hostname:port Number:databaseName
DB2 [Link].DB2Driver jdbc:db2:hostname:port Number/databaseName
Sybase [Link] jdbc:sybase:Tds:hostname: port Number/databaseName
All the highlighted part in URL format is static and you need to change only remaining part as per
your database setup.
Create Connection Object:
Using a database URL with a username and password:
[Link]() method used to create a connection object. It requires you to pass
a database URL, a username, and a password.
Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for the
database portion of the URL.
If you have a host at TCP/IP address [Link]/localhost with a host name of dmu, and your Oracle
listener is configured to listen on port 1521, and your database name is EMP, then complete database
URL would then be:
jdbc:oracle:thin:@dmu:1521:EMP
Now you have to call getConnection() method with appropriate username and password to get a
Connection object as follows:
String URL = "jdbc:oracle:thin:@dmu:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = [Link](URL, USER, PASS);
Closing JDBC connections:
At the end of your JDBC program, it is required explicitly close all the connections to the database to
end each database session. However, if you forget, Java's garbage collector will close the connection
when it cleans up stale/old objects.
16
Relying on garbage collection, especially in database programming, is very poor programming
practice. You should make a habit of always closing the connection with the close() method associated
with connection object.
To ensure that a connection is closed, you could provide a finally block in your code. A finally block
always executes, regardless if an exception occurs or not.
To close above opened connection you should call close() method as follows:
[Link]();
Explicitly closing a connection conserves DBMS resources, which will make your database
administrator happy.
For a better understanding, see the following example
// Create database using the ff parameters database name: hrmdb, user name: hrmdb ,password: hrmdb and
table name :emptable (eid,ename,efname,eage) and design the following jframeform
//import package
import [Link].*;
public class Employee extends [Link] {
Connection con;
Statement stmt;
ResultSet rs;
/** Creates new form Employee */
public Employee() {
initComponents();
17
DoConnect(); // method declaration used to connect database
public void DoConnect(){
try
//STEP 2: Register JDBC driver
Driver d = new [Link]();
[Link]( d );
[Link]("Driver Loaded");
//SETP 3 :Open connection to database
con=[Link]("jdbc:oracle:thin:@localhost:1521:xe", "hrmdb", "hrmdb"); //type 4
stmt=[Link](ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
// Step 4: Execute query
String sql="select * from emptable";
rs=[Link](sql);
// populate first record on the form
[Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
//to display on output windows
while ([Link]()) { //start at raw 2
String id=[Link](1);
String name=[Link](2);
[Link](id + " "+ name);
18
}catch(SQLException err){
[Link]([Link]());
//For First navigation button
try {
if(con!=null)
{ [Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
} catch(SQLException ex)
{ [Link](null,[Link]()); }
//for next navigation button
try {
if(con!=null)
{ [Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
} catch(SQLException ex)
[Link](null,[Link]());
19
//for previous navigation button
try {
if(con!=null)
{ [Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
} catch(SQLException ex)
{ [Link](null,[Link]()); }
//For Last navigation button
try {
if(con!=null)
{ [Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
} catch(SQLException ex)
[Link](null,[Link]());
//Save new data
20
try {
if(con!=null)
PreparedStatement pstmt=[Link]("insert into emptable values(?,?,?,?)");
String id1=[Link]();
String name=[Link]();
String fname=[Link]();
int age= [Link]([Link]());
[Link]();
[Link](1, id1);
[Link](2, name);
[Link](3, fname);
[Link](4, age);
[Link]();
[Link](null,"One row inserted");
} catch(SQLException ex)
[Link](null,[Link]());
//Delete record
String id1=[Link]();
try{
String sql = "DELETE FROM emptable WHERE eid=?";
PreparedStatement ps = [Link](sql);
[Link](1, id1);
int rowsDeleted = [Link]();
if (rowsDeleted > 0)
[Link]("A Record was deleted successfully!");
} catch (SQLException ex) {
21
[Link](null,[Link]());
}
//Search record by id
try{
String id1=[Link]();
String str="select * from emptable where eid='"+id1+"'";
rs= [Link](str);
[Link]();
[Link]([Link]("eid"));
[Link]([Link]("ename"));
[Link]([Link]("efname"));
[Link]([Link]([Link]("eage")));
[Link]("A Record is found successfully!");
} catch (SQLException ex) {
[Link](null,[Link]());
}
//update record
try{
String id=[Link]();
String name=[Link]();
String fname=[Link]();
int age= [Link]([Link]());
PreparedStatement ps=null;
String str="update emptable set ename=?,efname=?,eage=? where eid=?";
ps=[Link](str);
[Link](1, name);
[Link](2, fname);
[Link](3, age);
[Link](4, id);
[Link]();
[Link](null,"One row updated");
} catch (SQLException ex) {
[Link]([Link]()); }
}// end of employee class
22