You are on page 1of 22

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 javax.swing.JOptionPane; 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(java.awt.event.KeyEvent evt) {

if( (evt.getKeyChar() >= 'a' && evt.getKeyChar() <= 'z')||(evt.getKeyChar() >= 'A' && evt.getKeyChar() <= 'Z'))

txt1.setEditable(true);
else {
txt1.setEditable(false);
JOptionPane.showMessageDialog(null," please enter only letter");
txt1.setEditable(true);
}
}
//Number validation
private void txt2KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyChar() >= '0' && evt.getKeyChar() <= '9')
txt2.setEditable(true);

else {
txt2.setEditable(false);
JOptionPane.showMessageDialog(null," please enter only numeric digits(0-9)");
txt2.setEditable(true);
}
}

//Code for btndisplay button


// Right click on btndisplay and point to Events then point to Action and then Actionperformed
private void btndisplayActionPerformed(java.awt.event.ActionEvent evt)

2
{
String s1=txt1.getText();
txt3.setText(s1);
String s2=txt2.getText();
txt4.setText(s2);
}
private void btnclearActionPerformed(java.awt.event.ActionEvent evt)
{
txt1.setText(“ ”);
txt2.setText(“ “);
txt3.setText(“ “);
txt4.setText(“ “);
}

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(java.awt.event.ActionEvent evt)
{
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn1.getText();
txtnum1.setText(str);

3
} else
{ str= txtnum2.getText() + btn1.getText();
txtnum2.setText(str);
}
}
private void btn2ActionPerformed(java.awt.event.ActionEvent evt)
{
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn2.getText();
txtnum1.setText(str);
} else
{ str= txtnum2.getText() + btn2.getText();
txtnum2.setText(str);
}
}
private void btn3ActionPerformed(java.awt.event.ActionEvent evt)
{
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn3.getText();
txtnum1.setText(str);
} else
{ str= txtnum2.getText() + btn3.getText();
txtnum2.setText(str);
}
}
private void btn4ActionPerformed(java.awt.event.ActionEvent evt)
{
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn4.getText();
txtnum1.setText(str);
} else
{ str= txtnum2.getText() + btn4.getText();
txtnum2.setText(str);
}
}

private void btn5ActionPerformed(java.awt.event.ActionEvent evt)


{
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn5.getText();
txtnum1.setText(str);
} else
{ str= txtnum2.getText() + btn5.getText();
txtnum2.setText(str);
}

4
}
private void btn6ActionPerformed(java.awt.event.ActionEvent evt)
{
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn6.getText();
txtnum1.setText(str);
} else
{ str= txtnum2.getText() + btn6.getText();
txtnum2.setText(str);
}
}
private void btn7ActionPerformed(java.awt.event.ActionEvent evt)
{
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn7.getText();
txtnum1.setText(str);
} else
{ str= txtnum2.getText() + btn7.getText();
txtnum2.setText(str);
}
}
private void btn8ActionPerformed(java.awt.event.ActionEvent evt)
{
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn8.getText();
txtnum1.setText(str);
} else
{ str= txtnum2.getText() + btn8.getText();
txtnum2.setText(str);
}
}

private void btn9ActionPerformed(java.awt.event.ActionEvent evt)


{
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn9.getText();
txtnum1.setText(str);
} else
{ str= txtnum2.getText() + btn9.getText();
txtnum2.setText(str);
}
}
private void btn0ActionPerformed(java.awt.event.ActionEvent evt)
{

5
String str=null;
if(txtop.getText().equals(""))
{ str = txtnum1.getText() + btn0.getText();
txtnum1.setText(str);
} else
{ str= txtnum2.getText() + btn0.getText();
txtnum2.setText(str);
}
}

private void btndotActionPerformed(java.awt.event.ActionEvent evt)


{
String str;
if(txtop.getText().equals(""))
{
str = txtnum1.getText() + btndot.getText();
txtnum1.setText(str);
btndot.setEnabled(false);
}
else
{
str = txtnum2.getText() + btndot.getText();
txtnum2.setText(str);
btndot.setEnabled(false);
}

private void btnaddActionPerformed(java.awt.event.ActionEvent evt)


{
if(txtnum1.getText().equals(""))JOptionPane.showMessageDialog(null," Enter value in the first
textfield");
else{
txtop.setText("+");
btndot.setEnabled(true);
}
}

private void btnsubtActionPerformed(java.awt.event.ActionEvent evt)

{
if(txtnum1.getText().equals(""))JOptionPane.showMessageDialog(null," Enter value in the first
textfield");
else{
txtop.setText("-");

6
btndot.setEnabled(true);

}
private void btnmultActionPerformed(java.awt.event.ActionEvent evt) {
if(txtnum1.getText().equals(""))JOptionPane.showMessageDialog(null," Enter value in the first
textfield");
else{
txtop.setText("*");
btndot.setEnabled(true);
}
}

private void btndivActionPerformed(java.awt.event.ActionEvent evt)

{
if(txtnum1.getText().equals(""))JOptionPane.showMessageDialog(null," Enter value in the first
textfield");
else{
txtop.setText("/");
btndot.setEnabled(true);
}
}

private void btnmodActionPerformed(java.awt.event.ActionEvent evt)


{
if(txtnum1.getText().equals(""))JOptionPane.showMessageDialog(null," Enter value in the first
textfield");
else{
txtop.setText("%");
btndot.setEnabled(true);
}
}

private void btnequalActionPerformed(java.awt.event.ActionEvent evt) {


float val1=Float.parseFloat(txtnum1.getText());
float val2= Float.parseFloat(txtnum2.getText());
String oper=txtop.getText();
String result=null;
if(oper.equals("+"))
{ result= val1+val2;
txtresult.setText(Float.toString(result));
}
else if(oper.equals("-"))

7
{ result= val1-val2;
txtresult.setText(Float.toString(result));
}
else if(oper.equals("*"))
{ result= val1*val2;
txtresult.setText(Float.toString(result));
}
else if(oper.equals("/"))
{ if(val2==0) JOptionPane.showMessageDialog(null," Division by zero is not allowed");
else{
result= val1/val2;
txtresult.setText(Float.toString(result));
}
}
else if(oper.equals("%"))
{ result= val1%val2;
txtresult.setText(Float.toString(result));
}
}
private void btnclearActionPerformed(java.awt.event.ActionEvent evt) {
txtnum1.setText("");
txtnum2.setText("");
txtresult.setText("");
txtop.setText("");
btndot.setEnabled(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 Java.sql 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
java.sql.Driver 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 java.sql.* ; // for standard JDBC programs


import java.math.* ; // 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 oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

Database URL Formulation:


After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() 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 com.mysql.jdbc.Driver jdbc:mysql://hostname:port Number/ databaseName

15
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName

Sybase com.sybase.jdbc.SybDriver 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:
DriverManager.getConnection() 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 127.0.0.1/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 = DriverManager.getConnection(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:
conn.close();

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 java.sql.*;
public class Employee extends javax.swing.JFrame {
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 oracle.jdbc.driver.OracleDriver();

DriverManager.registerDriver( d );

System.out.println("Driver Loaded");

//SETP 3 :Open connection to database

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hrmdb", "hrmdb"); //type 4

stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

// Step 4: Execute query

String sql="select * from emptable";

rs=stmt.executeQuery(sql);

// populate first record on the form

rs.first();

txtid.setText(rs.getString("eid"));

txtname.setText(rs.getString("ename"));

txtfname.setText(rs.getString("efname"));

txtage.setText(Integer.toString(rs.getInt("eage")));

//to display on output windows

while (rs.next()) { //start at raw 2

String id=rs.getString(1);

String name=rs.getString(2);

System.out.println(id + " "+ name);

18
}catch(SQLException err){

System.out.println(err.getMessage());

//For First navigation button

try {

if(con!=null)

{ rs.first();

txtid.setText(rs.getString("eid"));

txtname.setText(rs.getString("ename"));

txtfname.setText(rs.getString("efname"));

txtage.setText(Integer.toString(rs.getInt("eage")));

} catch(SQLException ex)

{ JOptionPane.showMessageDialog(null,ex.getMessage()); }

//for next navigation button

try {

if(con!=null)

{ rs.next();

txtid.setText(rs.getString("eid"));

txtname.setText(rs.getString("ename"));

txtfname.setText(rs.getString("efname"));

txtage.setText(Integer.toString(rs.getInt("eage")));

} catch(SQLException ex)

JOptionPane.showMessageDialog(null,ex.getMessage());

19
//for previous navigation button

try {

if(con!=null)

{ rs.previous();

txtid.setText(rs.getString("eid"));

txtname.setText(rs.getString("ename"));

txtfname.setText(rs.getString("efname"));

txtage.setText(Integer.toString(rs.getInt("eage")));

} catch(SQLException ex)

{ JOptionPane.showMessageDialog(null,ex.getMessage()); }

//For Last navigation button

try {

if(con!=null)

{ rs.last();

txtid.setText(rs.getString("eid"));

txtname.setText(rs.getString("ename"));

txtfname.setText(rs.getString("efname"));

txtage.setText(Integer.toString(rs.getInt("eage")));

} catch(SQLException ex)

JOptionPane.showMessageDialog(null,ex.getMessage());

//Save new data

20
try {

if(con!=null)

PreparedStatement pstmt=con.prepareStatement("insert into emptable values(?,?,?,?)");

String id1=txtid.getText();

String name=txtname.getText();

String fname=txtfname.getText();

int age= Integer.parseInt(txtage.getText());

rs.afterLast();

pstmt.setString(1, id1);

pstmt.setString(2, name);

pstmt.setString(3, fname);

pstmt.setInt(4, age);

pstmt.executeUpdate();

JOptionPane.showMessageDialog(null,"One row inserted");

} catch(SQLException ex)

JOptionPane.showMessageDialog(null,ex.getMessage());

//Delete record

String id1=txtsearch.getText();

try{

String sql = "DELETE FROM emptable WHERE eid=?";

PreparedStatement ps = con.prepareStatement(sql);

ps.setString(1, id1);
int rowsDeleted = ps.executeUpdate();
if (rowsDeleted > 0)
System.out.println("A Record was deleted successfully!");
} catch (SQLException ex) {

21
JOptionPane.showMessageDialog(null,ex.getMessage());
}
//Search record by id
try{
String id1=txtsearch.getText();
String str="select * from emptable where eid='"+id1+"'";
rs= stmt.executeQuery(str);
rs.next();
txtid.setText(rs.getString("eid"));
txtname.setText(rs.getString("ename"));
txtfname.setText(rs.getString("efname"));
txtage.setText(Integer.toString(rs.getInt("eage")));
System.out.println("A Record is found successfully!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}

//update record
try{
String id=txtid.getText();
String name=txtname.getText();
String fname=txtfname.getText();
int age= Integer.parseInt(txtage.getText());
PreparedStatement ps=null;
String str="update emptable set ename=?,efname=?,eage=? where eid=?";
ps=con.prepareStatement(str);
ps.setString(1, name);
ps.setString(2, fname);
ps.setInt(3, age);
ps.setString(4, id);
ps.executeUpdate();
JOptionPane.showMessageDialog(null,"One row updated");
} catch (SQLException ex) {
System.out.println(ex.getMessage()); }
}// end of employee class

22

You might also like