Professional Documents
Culture Documents
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.
• 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
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”);
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
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”);
p.setLayout(L);
p.add(b1);
p.add(b2);
press me then me
f.setContentPane(p);
• Constructors
• JTextField()-
– Creates a new TextField
• JTextField(String text)
– Creates a new TextField initialized with the specified text.
• 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.
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
• 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:
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.”
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);
52
Image Icons, Keyboard Mnemonics, and Keyboard
Accelerators
JMenuItem jmiNew, jmiOpen;
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(){
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));
}
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
}
• 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
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.
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
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
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);
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
• 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
setSize(400,400);
setLayout(null);
setVisible(true);
}