You are on page 1of 139

Unit -5

EXPLORING SWING
AWT to Swing
• AWT: Abstract Windowing Toolkit
• import java.awt.*
• Swing: new with Java2
• import javax.swing.*
• Extends AWT
• new improved components
• Standard dialog boxes, tooltips, …
• Look-and-feel, skins
• Event listeners
Understanding what Swing Is
• Swing is a package that lets you create
applications that use a flashy Graphical User
Interface (or GUI) instead of a dull console
interface.
• The Swing API provides many different classes
for creating various types of user interface
elements.
SWING - Overview
• Swing API is a set of extensible GUI Components to ease the
developer's life to create JAVA based Front End/GUI
Applications.
• It is built on the top of AWT (Abstract Windowing Toolkit) API
and entirely written in java.
• It acts as a replacement of AWT API, since it has almost every
control corresponding to AWT controls.
• Unlike AWT, Java Swing provides platform-independent and
lightweight components.
Swing Set Demo
Swing Features
• Light Weight − Swing components are independent of
native Operating System's API as Swing API controls are
rendered mostly using pure JAVA code instead of
underlying operating system calls.
• Rich Controls − Swing provides a rich set of advanced
controls like Tree, TabbedPane, slider, colorpicker, and table
controls.
• Highly Customizable − Swing controls can be customized in
a very easy way as visual apperance is independent of
internal representation.
• Pluggable look-and-feel − SWING based GUI Application
look and feel can be changed at run-time, based on
available values.
AWT & Swing
Java AWT Java Swing
AWT components are platform- Java swing components
dependent. are platform-independent.

AWT components Swing components


are heavyweight. are lightweight.
AWT doesn't support pluggable Swing supports pluggable look
look and feel. and feel.
AWT provides less Swing provides more powerful
components than Swing. component ssuch as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
AWT doesn't follows Swing follows MVC. MVC(Model View
Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and view.
GUI Component API
• Java: GUI component = class

• Properties
JButton

• Methods

• Events
Using a GUI Component
1. Create it
• Instantiate object: b = new JButton(“press me”);
2. Configure it
• Properties: b.text = “press me”; [avoided in java]
• Methods: b.setText(“press me”);
3. Add it
• panel.add(b);
4. Listen to it JButton

• Events: Listeners
Anatomy of an Application GUI
GUI Internal structure

JFrame JFrame

JPanel
containers

JPanel
JButton

JButton JLabel
JLabel
Using a GUI Component 2
1. Create it
order
2. Configure it important
3. Add children (if container)
4. Add to parent (if not JFrame)
5. Listen to it
Build from bottom up
• Create: Listener

• Frame
• Panel JLabel JButton

• Components
• Listeners
• Add: (bottom up) JPanel

• listeners into components


• components into panel
• panel into frame
JFrame
Code
JFrame f = new JFrame(“frame1”);

JPanel p = new JPanel( );

JButton b = new JButton(“press me”);


press me

p.add(b);
press me

f.setContentPane(p);
f.show(); press me
Application Code
import javax.swing.*;

class hello {
public static void main(String[] args){
JFrame f = new JFrame(“frame1”);
JPanel p = new JPanel();
JButton b = new JButton(“press me”);

p.add(b); // add button to panel


f.setContentPane(p); // add panel to frame

f.show(); press me
}
}
Layout Managers
• Automatically control placement of
components in a panel
Layout Manager Heuristics
null FlowLayout GridLayout

none,
Left to right,
programmer
Top to bottom
sets x,y,w,h

BorderLayout CardLayout GridBagLayout


n

w e JButton
c One at a time

s
Combinations
JButton JButton
JFrame

n
JPanel: FlowLayout
JPanel: BorderLayout

JTextArea
Combinations

JButton JButton

JTextArea
Code: null layout
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
JButton b = new JButton(“press me”);

b.setBounds(new Rectangle(10,10, 100,50));


p.setLayout(null); // x,y layout
p.add(b);
f.setContentPane(p);
press me
Code: FlowLayout
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
FlowLayout L = new FlowLayout( );
JButton b1 = new JButton(“press me”);
JButton b2 = new JButton(“then me”);

p.setLayout(L);
p.add(b1);
p.add(b2);
press me then me
f.setContentPane(p);

Set layout mgr before adding components


Hierarchy of Java Swing classes
Methods of Component class
• public void add(Component c)
– add a component on another component.

• public void setSize(int width,int height)


– sets size of the component.

• public void setLayout(LayoutManager m)


– sets the layout manager for the component.

• public void setVisible(boolean b)


– -sets the visibility of the component. It is by
default false.
Simple Java Swing Example
import javax.swing.*;
public class FirstSwing {
FirstSwing ()
{
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
public static void main(String[] args) {
FirstSwing f=new FirstSwing();
}
}
JLabel class

• public class JLabel extends JComponent imple


ments SwingConstants, Accessible
Constructors
• JLabel()
– Creates a JLabel instance with no image and with
an empty string for the title.
• JLabel(String s)
– Creates a JLabel instance with the specified text.
JLabel class
Methods Description

It returns the text string


String getText()
that a label displays.
It defines the single line of
void setText(String text) text this component will
display.
void It sets the alignment of the
setHorizontalAlignment(int label's contents along the X
alignment) axis.
import javax.swing.*;
class LabelExample JLabel
{
LabelExample()
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel(“Label1");
l1.setBounds(50,50, 100,30);
l2=new JLabel(“label2");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{ LabelExample e=new LableExample ();
}
}
JTextField class
• public class JTextField extends JTextComponent implements Swing
Constants

• Constructors
• JTextField()-
– Creates a new TextField

• JTextField(String text)
– Creates a new TextField initialized with the specified text.

• JTextField(String text, int columns)


– Creates a new TextField initialized with the specified text and columns.

• JTextField(int columns)
– Creates a new empty TextField with the specified number of columns.
JTextField class
Methods Description
void addActionListener It is used to add the specified action
(ActionListener l) listener to receive action events from
this textfield.
Action getAction() It returns the currently set Action for
this ActionEvent source, or null if no
Action is set.
void setFont(Font f) It is used to set the current font.

Void removeActionListener It is used to remove the specified


(ActionListener l) action listener so that it no longer
receives action events from this
textfield.
import javax.swing.*;
class TextFieldExample
{ JTextField class
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to MCET");
t1.setBounds(50,100, 200,30);
t2=new JTextField(“CSE-Second Year”
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
JButton class

• public class JButton extends AbstractButton im


plements Accessible
Constructor
• JButton()
– It creates a button with no text and icon.
• JButton(String s)
– It creates a button with the specified text.
• JButton(Icon i)
– It creates a button with the specified icon
object.
JButton class
Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the


button.
Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the


button.
void addActionListener It is used to add the action listener to this
(ActionListener a) object.
import java.awt.event.*;
import javax.swing.*;
public class ButtonExp implements ActionListener {
JTextField tf; JFrame f;
ButtonExp(){
f=new JFrame("Button Example");
tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to MCET.");
}
public static void main(String[] args) {
ButtonExp b=new ButtonExp();
}
JButton class
import javax.swing.*; b1.addActionListener(this);
import java.awt.event.*; b2.addActionListener(this);
public class TextFieldExample implements f.add(tf1);f.add(tf2);f.add(tf3);
ActionListener{ f.add(b1);f.add(b2);
f.setSize(300,300);
JTextField tf1,tf2,tf3; f.setLayout(null);
JButton b1,b2; f.setVisible(true);
TextFieldExample(){ }
JFrame f= new JFrame(); public void actionPerformed(ActionEvent e)
{
tf1=new JTextField(); String s1=tf1.getText();
tf1.setBounds(50,50,150,20); String s2=tf2.getText();
tf2=new JTextField(); int a=Integer.parseInt(s1);
tf2.setBounds(50,100,150,20); int b=Integer.parseInt(s2);
int c=0;
tf3=new JTextField(); if(e.getSource()==b1){
tf3.setBounds(50,150,150,20); c=a+b;
tf3.setEditable(false); }else if(e.getSource()==b2){
b1=new JButton("+"); c=a-b;
}
b1.setBounds(50,200,50,50); String result=String.valueOf(c);
b2=new JButton("-"); tf3.setText(result);
b2.setBounds(120,200,50,50); }
public static void main(String[] args) {
new TextFieldExample();
}}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();

int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;

if(e.getSource()==b1) c=a+b;
else if(e.getSource()==b2) c=a-b;

String result=String.valueOf(c);
tf3.setText(result);
}
JTextArea class

• public class JTextArea extends JTextComponent


Constructor Description
JTextArea() Creates a text area that displays no
text initially.
JTextArea(String s) Creates a text area that displays
specified text initially.
JTextArea(int row, int column) Creates a text area with the
specified number of rows and
columns that displays no text
initially.
JTextArea(String s, int row, int Creates a text area with the
column) specified number of rows and
columns that displays specified text.
JTextArea class
Methods Description

void setRows(int rows) It is used to set specified
number of rows.
void setColumns(int cols) It is used to set specified
number of columns.
void setFont(Font f) It is used to set the specified
font.
void insert(String s, int position) It is used to insert the specified
text on the specified position.
void append(String s) It is used to append the given
text to the end of the
document.
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to MCET-CSE");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
Tutorial-1
• Write a java Program to count no of words in
textarea .
• Write a java program to create frame for
simple calculator.
import javax.swing.*;
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
public void actionPerformed(ActionEvent e){
l2=new JLabel(); String text=area.getText();
l2.setBounds(160,25,100,30); String words[]=text.split("\\s");
area=new JTextArea(); l1.setText("Words: "+words.length);
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
l2.setText("Characters: "+text.length());
b.setBounds(100,300,120,30); }
b.addActionListener(this); public static void main(String[] args) {
f.add(l1);f.add(l2);f.add(area);f.add(b); new TextAreaExample();
f.setSize(450,450);
f.setLayout(null);
}
f.setVisible(true); }
}
Swing-Menu
Menus
• Java provides several classes—
– JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, and
JRadioButtonMenuItem

• A JFrame or JApplet can hold a menu bar to which the pull-down


menus are attached.

• Menus consist of menu items that the user can select (or toggle
on or off). Menu bars can be viewed as a structure to support
menus.

45
Menu Item

Menu Bar

Menu
The JMenuBar Class
A menu bar holds menus; the menu bar can only be added
to a frame. Following is the code to create and add a
JMenuBar to a frame:

JFrame f = new JFrame();


f.setSize(300, 200);
f.setVisible(true);
JMenuBar mb = new JMenuBar();
f.setJMenuBar(mb);

47
The JMenu Class
You attach menus onto a JMenuBar. The following
code creates two menus, File and Help, and adds
them to the JMenuBar mb:
JMenu fileMenu = new JMenu("File", false);
JMenu helpMenu = new JMenu("Help", true);
mb.add(fileMenu);
mb.add(helpMenu);

48
The JMenuItem Class
You add menu items on a menu. The following
code adds menu items and item separators in
menu fileMenu:
fileMenu.add(new JMenuItem("new"));
fileMenu.add(new JMenuItem("open"));
fileMenu.addSeparator();
fileMenu.add(new JMenuItem("print"));
fileMenu.add(new JMenuItem("exit"));
fileMenu.addSeparator();

49
Submenus
You can add submenus into menu items. The following code adds the submenus “Unix,”
“NT,” and “Win95” into the menu item “Software.”

JMenu softwareHelpSubMenu = new JMenu("Software");

JMenu hardwareHelpSubMenu = new JMenu("Hardware");

helpMenu.add(softwareHelpSubMenu);

helpMenu.add(hardwareHelpSubMenu);

softwareHelpSubMenu.add(new JMenuItem("Unix"));

softwareHelpSubMenu.add(new JMenuItem("NT"));

softwareHelpSubMenu.add(new JMenuItem("Win95"));

50
Check Box Menu Items
helpMenu.add(new JCheckBoxMenuItem("Check it"));

51
Radio Button Menu Items
JMenu colorHelpSubMenu = new JMenu("Color");
helpMenu.add(colorHelpSubMenu);

JRadioButtonMenuItem jrbmiBlue, jrbmiYellow, jrbmiRed;


colorHelpSubMenu.add(jrbmiBlue = new JRadioButtonMenuItem("Blue"));
colorHelpSubMenu.add(jrbmiYellow = new JRadioButtonMenuItem("Yellow"));
colorHelpSubMenu.add(jrbmiRed = new JRadioButtonMenuItem("Red"));

ButtonGroup btg = new ButtonGroup();


btg.add(jrbmiBlue);
btg.add(jrbmiYellow);
btg.add(jrbmiRed);

52
Image Icons, Keyboard Mnemonics, and Keyboard
Accelerators
JMenuItem jmiNew, jmiOpen;

fileMenu.add(jmiNew = new JMenuItem("New"));

fileMenu.add(jmiOpen = new JMenuItem("Open"));

jmiNew.setIcon(new ImageIcon("image/new.gif"));

jmiOpen.setIcon(new ImageIcon("image/open.gif"));

helpMenu.setMnemonic('H');

fileMenu.setMnemonic('F');

jmiNew.setMnemonic('N');

jmiOpen.setMnemonic('O');

53
Example: Using Menus
• Create a user interface that performs
arithmetic. The interface contains labels and
text fields for Number 1, Number 2, and Result.
The Result box displays the result of the
arithmetic operation between Number 1 and
Number 2.

54
Example: Using Menus
Problem: Create a user interface that performs arithmetic. The
interface contains labels and text fields for Number 1,
Number 2, and Result. The Result box displays the result of
the arithmetic operation between Number 1 and Number 2.

55
import javax.swing.*;
import java.awt.event.*;
class MenuExample extends JFrame implements ActionListener
{ JMenu menu; JMenuItem i1, i2, i3, i4, i5;
JTextField f1,f2,f3;
MenuExample(){

JFrame f= new JFrame("Menu and MenuItem Example");


f1=new JTextField(); f2=new JTextField(); f3=new JTextField();
f1.setBounds(50,50,50,50); f2.setBounds(50,110,50,50); f3.setBounds(50,170,50,50);

JMenuBar mb=new JMenuBar();


menu=new JMenu("Menu");
i1=new JMenuItem("Add"); i2=new JMenuItem("Sub ");
i3=new JMenuItem("Multiply"); i4=new JMenuItem("Divide");
i5=new JMenuItem("Exit ");
menu.add(i1); menu.add(i2); menu.add(i3); menu.add(i4); menu.add(i5); mb.add(menu);
i1.addActionListener(this); i2.addActionListener(this); i3.addActionListener(this);
i4.addActionListener(this); i5.addActionListener(this);
f.setJMenuBar(mb); f.setSize(400,400); f.setLayout(null); f.setVisible(true);
}
public void actionPerformed( ActionEvent e )
{String s1=f1.getText(); String s2=f2.getText(); int a=
Integer.parseInt(s1);int b= Integer.parseInt(s2); int c=0;

if(e.getSource()==i1) {c=a+b;}
else if(e.getSource()==i2) {c=a-b;}
else if(e.getSource()==i3) {c=a*b;}
else if(e.getSource()==i4) {c=a/b;}
else if(e.getSource()==i5) {System.exit(0);}

f3.setText(String.valueOf(c));
}

public static void main(String args[])


{
new MenuExample();
}}
Application + Applet
import javax.swing.*;

class helloApp {
Command line Browser
public static void main(String[] args){
// create Frame and put my mainPanel in it
JFrame f = new JFrame(“title”);
mainPanel p = new mainPanel();
f.setContentPane(p);
f.show(); or
}
JFrame JApplet
}

class helloApplet extends JApplet {


public void init(){ contentPane
// put my mainPanel in the Applet
mainPanel p = new mainPanel();
getContentPane().add(p);
}
}

// my main GUI is in here:


class mainPanel extends JPanel { JPanel
mainPanel(){
setLayout(new FlowLayout());
JButton b = new JButton(“press me”);
add(b);
}
}
JButton
Applets
JApplet
• JApplet is like a JFrame
• Already has a panel
• Access panel with JApplet.getContentPane( )
contentPane
import javax.swing.*;

class hello extends JApplet {


public void init(){ JButton
JButton b = new JButton(“press me”);
getContentPane().add(b);
}
}
Applet Methods
• Called by browser:

• init( ) - initialization
• start( ) - resume processing (e.g. animations)
• stop( ) - pause
• destroy( ) - cleanup
• paint( ) - redraw stuff (‘expose’ event)
Applet Security
• No read/write on client machine
• Can’t execute programs on client machine
• Communicate only with server
• “Java applet window” Warning
Swing

Jlabel,JButton,JTextField,JTextArea
JDBC –
Java DataBase Connectivity
Java and the database
• Database is used to store data.
• It is also known as persistent storage as the
data is stored and can be retrieved anytime.
• Java and database are used almost everywhere
to store persistent data and retrieve it when
required.
SQL
• Information stored in the database is in tables
and the language used to query information
from the database is SQL.
• Using SQL we can query a table based on the
requirement.
What is JDBC?

JDBC provides Java applications with access to most database systems via
SQL
The architecture and API closely resemble Microsoft's ODBC
JDBC 1.0 was originally introduced into Java 1.1
JDBC 2.0 was added to Java 1.2
JDBC is based on SQL-92

JDBC classes are contained within the java.sql package


There are few classes
There are several interfaces
JDBC Architecture

With JDBC, the application programmer uses


the JDBC API
The developer never uses any proprietary
APIs
• Any proprietary APIs are implemented by a
JDBC driver
• There are 4 types of JDBC Drivers
69
JDBC Drivers

There are 4 types of JDBC Drivers


Type 1 - JDBC-ODBC Bridge
Type 2 - JDBC-Native Bridge
Type 3 - JDBC-Net Bridge
Type 4 - Direct JDBC Driver
Type 1 only runs on platforms where ODBC is available
ODBC must be configured separately
Type 2 Drivers map between a proprietary Database API
and the JDBC API

Type 3 Drivers are used with middleware products


Type 4 Drivers are written in Java
In most cases, type 4 drivers are preferred
JDBC Drivers

Advantages:
easy to use.
can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC function calls.
The ODBC driver needs to be installed on the client machine.
JDBC Drivers

Advantage:
•performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
•The Native driver needs to be installed on the each client machine.
•The Vendor client library needs to be installed on client machine.
JDBC Drivers

Advantage:
No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
JDBC Drivers

Advantage:
Better performance than all other drivers.
No software is required at client side or server
side.
Disadvantage:
Drivers depends on the Database.
JDBC Classes

DriverManager
Manages JDBC Drivers
Used to Obtain a connection to a Database
Commonly used methods of DriverManager class:
1) public static void registerDriver(Driver driver): is used to register
the given driver with DriverManager.

2) public static void deregisterDriver(Driver driver): is used to


deregister the given driver (drop the driver from the list) with
DriverManager

3) public static Connection getConnection(String url): is used to


establish the connection with the specified url.
4) public static Connection getConnection(String url,String
userName,String password): is used to establish the connection
with the specified url, username and password
JDBC Interfaces

Connection
Statements
Resultset
Preparedstatment
ResultsetMetaData
DatabaseMetaData
JDBC Interfaces

Connection
Represents a connection to a specific database
Used for creating statements
Used for managing database transactions
Used for accessing stored procedures
Used for creating callable statements
JDBC Interfaces

1) public Statement createStatement(): creates a


statement object that can be used to execute SQL
queries.
2) public Statement createStatement(int
resultSetType,int resultSetConcurrency): Creates a
Statement object that will generate ResultSet objects
with the given type and concurrency.
3) public void setAutoCommit(boolean status): is
used to set the commit status.By default it is true.
4) public void commit(): saves the changes made
since the previous commit/rollback permanent.
5) public void rollback(): Drops all changes made
since the previous commit/rollback.
6) public void close(): closes the connection and
Releases a JDBC resources immediately.
JDBC Interfaces

Statement
Used for executing SQL statements against the
database
1) public ResultSet executeQuery(String sql): is
used to execute SELECT query. It returns the object of
ResultSet.
2) public int executeUpdate(String sql): is used to
execute specified query, it may be create, drop, insert,
update, delete etc.
3) public boolean execute(String sql): is used to
execute queries that may return multiple results.
4) public int[] executeBatch(): is used to execute
batch of commands.
JDBC Interfaces

ResultSet
Represents the result of an SQL statement
Provides methods for navigating through the resulting data
1) public boolean next(): is used to move the cursor to the
one row next from the current position.
2) public boolean previous(): is used to move the cursor to
the one row previous from the current position.
3) public boolean first(): is used to move the cursor to the
first row in result set object.
4) public boolean last(): is used to move the cursor to the
last row in result set object.
5) public boolean absolute(int row): is used to move the
cursor to the specified row number in the ResultSet object.
JDBC Interfaces

. 6) public boolean relative(int row): is used to move


the cursor to the relative row number in the ResultSet
object, it may be positive or negative.
7) public int getInt(int columnIndex): is used to return
the data of specified column index of the current row as
int.
8) public int getInt(String columnName): is used to
return the data of specified column name of the current
row as int.
9) public String getString(int columnIndex): is used
to return the data of specified column index of the
current row as String.
10) public String getString(String columnName): is
used to return the data of specified column name of the
current row as String
JDBC Interfaces

PreparedStatement
Similar to a stored procedure
An SQL statement (which can contain parameters) is compiled and
stored in the database

public void setInt(int paramIndex, int value) sets the integer value to the given
parameter index.
public void setString(int paramIndex, String value)sets the String value to the
given parameter index.
public void setFloat(int paramIndex, float value)sets the float value to the given
parameter index.
public void setDouble(int paramIndex, double value)sets the double value to the
given parameter index.
public int executeUpdate()executes the query. It is used for create, drop, insert,
update, delete etc.
public ResultSet executeQuery()executes the select query. It returns an instance
of ResultSet
JDBC Interfaces

ResultSetMetaData
Provides information about the data contained within a
ResultSet
public int getColumnCount()throws SQLExceptionit
returns the total number of columns in the ResultSet
object.
public String getColumnName(int index)throws
SQLExceptionit returns the column name of the
specified column index.
public String getColumnTypeName(int
index)throws SQLExceptionit returns the column type
name for the specified index.
public String getTableName(int index)throws
SQLExceptionit returns the table name for the
specified column index.
JDBC Interfaces

DatabaseMetaData
Provides access to a database's system catalogue
public String getDriverName()throws SQLException: it returns the name
of the JDBC driver.
public String getDriverVersion()throws SQLException: it returns the
version number of the JDBC driver.
public String getUserName()throws SQLException: it returns the
username of the database.
public String getDatabaseProductName()throws SQLException: it
returns the product name of the database.
public String getDatabaseProductVersion()throws SQLException: it
returns the product version of the database.
public ResultSet getTables(String catalog, String schemaPattern,
String tableNamePattern, String[] types)throws SQLException: it returns
the description of the tables of the specified catalog. The table type can be
TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
Basic steps to use a database in Java
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections

85
1. Establish a connection
• import java.sql.*;
• Load the vendor specific driver
– Class.forName("oracle.jdbc.driver.OracleDriver");
• What do you think this statement does, and how?
• Dynamically loads a driver class, for Oracle database
• Make the connection
– Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@oracle-prod:1521:OPROD", username,
passwd);
• What do you think this statement does?
• Establishes connection to database by obtaining
a Connection object
86
2. Create JDBC statement(s)
• Statement stmt = con.createStatement() ;
• Creates a Statement object for sending SQL statements to the
database

87
Executing SQL Statements
• String createtab = "Create table tname " +
"(SSN Integer not null, Name VARCHAR(32), "
+ "Marks Integer)";
stmt.executeUpdate(createtab);

• String insertrow = "Insert into Lehigh values“ +


"(123456789,abc,100)";
stmt.executeUpdate(insertrow);

88
Get ResultSet
String querytab = "select * from tname";

ResultSet rs = Stmt.executeQuery(querytab);

while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}
89
Close connection
• stmt.close();
• con.close();

90
Handling Errors with Exceptions
• Programs should recover and leave the database in a
consistent state.
• If a statement in the try block throws an exception or
warning, it can be caught in one of the corresponding
catch statements
• How might a finally {…} block be helpful here?
• E.g., you could rollback your transaction in a
catch { …} block or close database connection and free
database related resources in finally {…} block

91
ODBC driver
• Click on the Start Menu.
• Select Control Panel.
• Select Administrative Tools and double click the
Data Sources (ODBC) icon.
• Click Add, Select the Microsoft Access Driver
(.mdb) and click Finish.
• Type a name, Select a database or create one
and click OK. You're done. Celebrate.

92
Sample program
import java.sql.*;
Import sun.jdbc.odbc.*;
public class Test {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //dynamic
loading of driver
Connection con = DriverManager.getConnection( “jdbc:odbc:
myrep”);
Statement s = con.createStatement();
s.execute("create table TEST12345 ( firstcolumn integer )");
s.execute("insert into TEST12345 values(1)");
s.execute("select firstcolumn from TEST12345");

93
Sample program(cont)
ResultSet rs = s.getResultSet();
if (rs != null) // if rs == null, then there is no ResultSet to view
while ( rs.next() ) // this will step through our data row-by-row
{
System.out.println("Data from column_name: " + rs.getString(1) );
}
s.close(); // close Statement to let the database know we're done with it
con.close(); //close connection
}
catch (Exception err) { System.out.println("ERROR: " + err); }
}
}

94
Unit -5
Event Handling
Introduction
• Applets are event-driven programs that use a
GUI to interact with the user
• Any GUI application will be event driven
• Supported in “java.awt.event” class
• E.g.., Mouse click, Keyboard hit, button, scroll
bar, or check box controls…
Introduction
2 ways to handle events
• Traditional approach - By Java version 1.0
– An event, after generated, was propagated up the
containment hierarchy of listeners until it was handled
by a component
– The other component’s time is hence wasted
• Modern Approach - Beginning with Java versions 1.1
– listeners must register with a source in order to
receive an event notification.
– Hence notifications are sent only to listeners that
want to receive them
The Delegation Event Model
• Modern approach of event handling follows –
Delegation event model
• “A source generates an event and sends it to one
or more listeners”
– The listener simply waits until it receives an event
– Once an event is received, the listener processes the
event and then returns the response
• Advantage: User Interface logic is separated from
Application logic
– User interface delegates the processing of event to
another piece of code
The Delegation Event Model
Application logic
User Interface logic

Events
Application
User Interface
Interface
(Source) (Listeners)
Response

Process the Event


Events
• An event is an object that describes a state
change in a source
• Generated as a consequence of a person
interacting with the elements in a graphical user
interface
– E.g.., Mouse clicks, user enters key, selecting a menu
• Events may also occur that are not directly
caused by interactions with a user interface
– E.g.., when a timer expires, a counter exceeds a value
Event Sources
• A source is an object that generates an event
• This occurs when the internal state of that object
changes in some way.
• Sources may generate more than one type of event
• A source must register listeners using a registration
method:
– public void addTypeListener(TypeListener el)
where Type – Name of the Listener
E.g.., addKeyListener( ), addMouseMotionListener( )
• Removing listeners:
– public void removeTypeListener(TypeListener el)
Event Listeners
• A listener is an object that is notified when an
event occurs
• 2 requirements:
– It must have been registered with one or more
sources to receive notifications
– it must implement methods to receive and
process these notifications
• The methods are found in java.awt.event
Event Classes
• The root of the Java event class hierarchy is
EventObject, which is in java.util
• Constructor EventObject(Object src)
– src is the object that generates this event
• It has 2 methods:
– getSource( )  returns the source of the event
– toString( )  returns the string equivalent of the
event
AWTEvent Class
• The AWTEvent, defined within the java.awt
package, is a subclass of EventObject
• It is the superclass of all AWT-based events
used by the delegation event model.
• Method: int getID( )
– used to determine the type of the event
Event Classes
Event Classes
a) The ActionEvent Class
• Generated when:
– A button is pressed,
– A list item is double-clicked, or
– A menu item is selected
• 3 Constructors:
– ActionEvent(Object src, int type, String cmd)
– ActionEvent(Object src, int type, String cmd, int
modifiers)
– ActionEvent(Object src, int type, String cmd, long
when, int modifiers)
• Src  source; typetype of event; cmd  command;
modifiers  which modifiers are pressed ALT, CTRL, META
and or SHIFT; when  when the event occurred
• Command name, modifiers and time values are
obtained by:
– String getActionCommand( )
– int getModifiers( )
– long getWhen( )
b) The AdjustmentEvent Class
• Generated by a scroll bar; 5 types of adjustment events

• An integer constant: ADJUSTMENT_VALUE_CHANGED


• Constructor:
– AdjustmentEvent(Adjustable src, int id, int type, int
data)
• Getting the source object, type and id:
Adjustable getAdjustable( ); int getAdjustmentType( );
int getValue( )
c) The ComponentEvent Class
• Generated when the size, position, or visibility of a
component is changed.
• 4 types of component events

• Constructor: ComponentEvent(Component src, int type)


• Source object is obtained by:
Component getComponent( )
• ComponentEvent is the superclass of
– ContainerEvent,
– FocusEvent,
– KeyEvent,
– MouseEvent,
– WindowEvent.
d) The ContainerEvent Class
• Generated when a component is added to or
removed from a container
• Two types of container events – hence 2 integers:
– COMPONENT_ADDED and COMPONENT_REMOVED
• Constructor:
– ContainerEvent(Component src, int type, Component
comp)
• Src  main container;
• comp component that is added/removed
• Getting Container and Component:
– Container getContainer( ); Component getChild( )
e) The FocusEvent Class
• Generated when a component gains or loses input focus.
• Integer constants: FOCUS_GAINED and FOCUS_LOST
• 3 constructors:
– FocusEvent(Component src, int type)
– FocusEvent(Component src, int type, boolean temporaryFlag)
– FocusEvent(Component src, int type, boolean temporaryFlag,
Component other)
• temporaryFlag  is set to true if the focus event is temporary
• Other  other component involved in the focus change
• Getting other component and temporary flag
– Component getOppositeComponent( ); boolean isTemporary( )
f) The InputEvent Class
• It’s a abstract class; subclass of ComponentEvent and is the
superclass for component input events such as:
– KeyEvent and MouseEvent
• Methods used to test if a modifier was pressed at the time an event
is generated:
– boolean isAltDown( )
– boolean isAltGraphDown( )
– boolean isControlDown( )
– boolean isMetaDown( )
– boolean isShiftDown( )
• int getModifiers( ) – Used to obtain a value that contains all of the
original modifier flags
• int getModifiersEx( ) – Used to obtain the extended modifiers
g) The ItemEvent Class
• Generated when
– a check box or a list item is clicked or
– a checkable menu item is selected or deselected
• Three integer constants: SELECTED, DESELECTED
and ITEM_STATE_CHANGED
• Constructor:
– ItemEvent(ItemSelectable src, int type, Object entry,
int state)
• Src source (list or choice element); entry the specific item
that generated the item event; state  current state of item
The above entries are obtained using:
• Object getItem( )
• ItemSelectable getItemSelectable( )
• int getStateChange( )
h) The KeyEvent Class
• Generated when keyboard input occurs
• 3 types of events and integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED
• KEY_TYPED - occurs only when a character is generated (not
for shift, ctrl, alt buttons)
• Constructor:
KeyEvent(Component src, int type, long when, int
modifiers, int code, char ch)
• Code  VK codes/ VK_UNDEFINED (for shift/alt keys)
• Char  character pressed/CHAR_UNDEFINED
• The above parameters are obtained using:
– char getKeyChar( ); int getKeyCode( )
i) The MouseEvent Class
• Eight types of mouse events

• Constructor:
– MouseEvent(Component src, int type, long when, int
modifiers, int x, int y, int clicks, boolean triggersPopup)
– x and y  The coordinates of the mouse; Clicks  The click count
– triggersPopup flag  indicates if this event causes a pop-up menu to
appear
• Other methods:
– int getX( ) and int getY( ) or Point getPoint( )  position reg the
component
– void translatePoint(int x, int y)  changes the location of the event
– int getClickCount( ); boolean isPopupTrigger( )
– int getButton( )  returns a value that represents the button that
caused the event

– Some other methods in Java 1.6:


Point getLocationOnScreen( ); int getXOnScreen( ); int getYOnScreen( )
j) The MouseWheelEvent Class
• It is a subclass of MouseEvent
• Used for scrolling.
• Constructor: MouseWheelEvent(Component
src, int type, long when, int modifiers, int x, int
y, int clicks, boolean triggersPopup, int
scrollHow, int amount, int count)
– scrollHow  type of scroll (Block or Unit); Amount
 number of units to scroll; count  number of
rotational units that the wheel moved
• Other methods:
– int getWheelRotation( )
– int getScrollType( )
– int getScrollAmount( )
k) The TextEvent Class
• Generated by text fields and text areas when
characters are entered by a user or program
• Integer constant: TEXT_VALUE_CHANGED
• Constructor: TextEvent(Object src, int type)
l) The WindowEvent Class
• 10 types of window events:
• Constructors
– WindowEvent(Window src, int type)
– WindowEvent(Window src, int type, Window other)
– WindowEvent(Window src, int type, int fromState, int toState)
– WindowEvent(Window src, int type, Window other, int fromState, int
toState)
• other  the opposite window when a focus or activation event
occurs
• fromState  the prior state of the window, toState  the new
state
• Other methods:
– Window getWindow( ); Window getOppositeWindow( );
int getOldState( ); int getNewState( )
Sources of Events
Event Listener Interfaces
• a) The ActionListener Interface:
– void actionPerformed(ActionEvent ae)
• b) The AdjustmentListener Interface
– void adjustmentValueChanged(AdjustmentEvent
ae)
• c) The ComponentListener Interface
– void componentResized(ComponentEvent ce)
– void componentMoved(ComponentEvent ce)
– void componentShown(ComponentEvent ce)
– void componentHidden(ComponentEvent ce)
• d) The ContainerListener Interface
– void componentAdded(ContainerEvent ce)
– void componentRemoved(ContainerEvent ce)
• e) The FocusListener Interface
– void focusGained(FocusEvent fe)
– void focusLost(FocusEvent fe)
• f) The ItemListener Interface
– void itemStateChanged(ItemEvent ie)
• g) The KeyListener Interface
– void keyPressed(KeyEvent ke)
– void keyReleased(KeyEvent ke)
– void keyTyped(KeyEvent ke)
• h) The MouseListener Interface
– void mouseClicked(MouseEvent me)
– void mouseEntered(MouseEvent me)
– void mouseExited(MouseEvent me)
– void mousePressed(MouseEvent me)
– void mouseReleased(MouseEvent me)
• i) The MouseMotionListener Interface
– void mouseDragged(MouseEvent me)
– void mouseMoved(MouseEvent me)
• j) The MouseWheelListener Interface
– void mouseWheelMoved(MouseWheelEvent
mwe)
• k) The TextListener Interface
– void textChanged(TextEvent te)
• l) The WindowFocusListener Interface
– void windowGainedFocus(WindowEvent we)
– void windowLostFocus(WindowEvent we)
• m) The WindowListener Interface
– void windowActivated(WindowEvent we)
– void windowClosed(WindowEvent we)
– void windowClosing(WindowEvent we)
– void windowDeactivated(WindowEvent we)
– void windowDeiconified(WindowEvent we)
– void windowIconified(WindowEvent we)
– void windowOpened(WindowEvent we)
Using Delegation Event Model
• 2 step process:
1. Implement the appropriate interface in the
listener
2. Implement code to register and unregister (if
necessary) the listener – as a recipient for the
event notifications
• If source code generates multiple event types -
Each event must be registered separately
• Also one listener may be executed for multiple
events
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label(); l.setBounds(20,50,100,20); add(l);


setSize(300,300); setLayout(null); setVisible(true);
}
public void mouseClicked(MouseEvent e) { l.setText("Mouse Clicked"); }
public void mouseEntered(MouseEvent e) { l.setText("Mouse Entered");}
public void mouseExited(MouseEvent e) { l.setText("Mouse Exited"); }
public void mousePressed(MouseEvent e) { l.setText("Mouse Pressed"); }
public void mouseReleased(MouseEvent e) { l.setText("Mouse Released"); }
}
public static void main(String[] args) {
new MouseListenerExample();
}
• }
Example Handle Mouse Events
• Implement the MouseListener interfaces.
• The program does the following:
– Displays the current coordinates of the mouse in
the applet’s status window.
– Displays “Mouse pressed” each time the mouse is
pressed.
– Displays “Mouse Released” each time the mouse
is released.
– Displays “MouseClicked” each time the mouse
button is clicked.
b) Handling Keyboard Events
• Events Generated:
– KEY_PRESSED
– KEY_RELEASED
– KEY_TYPED
• Handlers (listeners) invoked:
– keyPressed()
– keyReleased()
– keyTyped()
• Refer SampleKey.java
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener{
Label l;
TextArea area;
KeyListenerExample(){

l=new Label(); l.setBounds(20,50,100,20);


area=new TextArea(); area.setBounds(20,80,300,300); area.addKeyListener(this);
add(l);add(area);
setSize(400,400); setLayout(null); setVisible(true);
}
public void keyPressed(KeyEvent e) { l.setText("Key Pressed"); }
public void keyReleased(KeyEvent e) { l.setText("Key Released"); }
public void keyTyped(KeyEvent e) { l.setText("Key Typed"); }

public static void main(String[] args) {


new KeyListenerExample();
}
}
Window Listener
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample extends Frame implements WindowListener{
WindowExample(){
addWindowListener(this);

setSize(400,400);
setLayout(null);
setVisible(true);
}

public static void main(String[] args) {


new WindowExample();
}
Window Listener
public void windowActivated(WindowEvent arg0) { System.out.println("activated"); }
public void windowClosed(WindowEvent arg0) { System.out.println("closed"); }
public void windowClosing(WindowEvent arg0) {
System.out.println("closing"); dispose();
}
public void windowDeactivated(WindowEvent arg0) { System.out.println("deactivated");
}
public void windowDeiconified(WindowEvent arg0) { System.out.println("deiconified");
}
public void windowIconified(WindowEvent arg0) { System.out.println("iconified"); }
public void windowOpened(WindowEvent arg0) { System.out.println("opened");
}
}
Window Listener

You might also like