Professional Documents
Culture Documents
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.
//Letter validation,Right click on txt1,then point to Events then point to Key finally select KeyPessed
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);
}
}
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(“ “);
}
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.
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);
}
}
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);
}
}
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);
}
}
{
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);
}
}
{
if(txtnum1.getText().equals(""))JOptionPane.showMessageDialog(null," Enter value in the first
textfield");
else{
txtop.setText("/");
btndot.setEnabled(true);
}
}
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:
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:
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.
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.
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.
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.
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.
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.
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:
You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as the
one provided by Microsoft.
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);
}
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.
15
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@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.
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:
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.
// 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
try
DriverManager.registerDriver( d );
System.out.println("Driver Loaded");
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=stmt.executeQuery(sql);
rs.first();
txtid.setText(rs.getString("eid"));
txtname.setText(rs.getString("ename"));
txtfname.setText(rs.getString("efname"));
txtage.setText(Integer.toString(rs.getInt("eage")));
String id=rs.getString(1);
String name=rs.getString(2);
18
}catch(SQLException err){
System.out.println(err.getMessage());
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()); }
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()); }
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());
20
try {
if(con!=null)
String id1=txtid.getText();
String name=txtname.getText();
String fname=txtfname.getText();
rs.afterLast();
pstmt.setString(1, id1);
pstmt.setString(2, name);
pstmt.setString(3, fname);
pstmt.setInt(4, age);
pstmt.executeUpdate();
} catch(SQLException ex)
JOptionPane.showMessageDialog(null,ex.getMessage());
//Delete record
String id1=txtsearch.getText();
try{
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