Sie sind auf Seite 1von 18

Event-driven programming

The actions using the GUI for a window-based program or an applet-clicking a menu item or button, moving the mouse and so on- are first identified by the OS For each action, the OS determines which of the programs currently running on the computer should know about it, and passes the action on to that program The signals that a program receives from the OS as a result of the actions are called events A window-based program is called a event-driven program, because the sequences of events are created as a result of the interaction with the GUI drives and determines what happens in the program

Javas Event-Delegation Model

In Java events are objects. The java.awt.event package defines a rich hierarchy of event types. Through this package, instances of various event classes are constructed when users use GUI components How to handle the event that is generated depends on the user Eg, when a user clicks on a button, the system constructs an instance of the class ActionEvent, in which it stores details about the event

Three options
Ignore the event Have the event handled by the component where the event originated Delegate event handling to some other object or objects, called listeners

Handling the Events in the Originating Components

A self-Contained component is the one that handles the event that it generates

None of the AWT components are self-contained

For a component to handle its own events, a subclass needs to be created. The subclass needs to do two things:
Get ready to receive events by calling its enableEvents() method Implement a processActionEvent() method, which will be called when an event is received

The class AWTEvent is a subclass of java.util.EventObject.

It defines a method getSource(), which returns the object that is the source of an event as type Object. This method is inherited by all the event classes
The class AWTEvent defines constants, which are public final values identifying various events. They are named in the form of the event name in capitals letters, followed by _MASK

Enabling Events
The enable events method is inherited from the component class Any component can elect to handle its own events. Call the enableEvents() method for the component and pass an argument defining the events which the components has to handle.


Prog demonstrating use of SelfButton


Delegating the Event

If a button is clicked, then the button is the source of this event. Therefore the source object is in this case Button object When the button is clicked, it will create a new object that represents and identifies this event- in this case an object of type ActionEvent. This object contains information about the event and its source Any event that is passed will be represented by a particular event object and this object will be passed as an argument to the method that is to handle the event. In this case it is actionPerformed() The event object corresponding to the button click will be passed to any listener object a listener object being simply an object that listens for particular events. A listener is defined by making the class implement a listener interface and creating objects of any class listener

Delegating the Event

There are variety of listener interfaces In this case the ActionListener interface needs to be implemented to receive the event from the button The code that is to receive this event object and respond to the event is implemented in a method declared in the listener interface.

Eg, actionPerformed() method in the ActionListener interface is called when the event occurs, and the event object is passed as an argument
The listener object has to be connected to the event that has to be dealt with A listener object can be registered with a source by calling a particular method in the source object. In this case, the addActionListener() method is called for the Button object, and the listener objects are passed as an argument to the method

Delegating the Event

public class Action Handler implements ActionListener { // class member //constructor button.addActionListener(this); void actionPerformed(ActionEvent ae) { //handle the event.. }
Passed to


ActionEvent object

Button Click

The listener Connects to the event source by calling addActionListener() method for the source object



Handling Events
Prog Output

Program to create an applet using buttons and text fields and place them on panels. The applet uses border layout. On click of button the background color of the applet is set to the button head. On click of the SET button the background color is set to the RGB value specified in the three text field Prog Output

Exercise 2
Use the form created in exercise1 of class1. Add FocusListener to TextFields, so that when a TextField gains focus, its background color becomes blue and becomes white when the focus is lost. Add ItemListener to the list and choice, so that the selected items of list and choice are displayed. The list and choice get activated, only when the user selects the computer proficient checkbox. Use adapter class to dispose the frame. Add ActionListener to the submit button, which clears the TextFields when pressed. The menu item New Record should generate a FileDialogBox when selected. Create an applet that has a choice and a list object. The choice object has three items as Television, Music System, cars. For each item selected in choice there is a corresponding list of brands available for that product. Set the text field, with the items selected in the choice and list.

Java Database Connectivity

The Connectivity model being used:

Java Application The User Interface

32-bit ODBC Oracle driver

The Oracle database & Its tables

Javas Driver Manager, Responsible for setting up the JDBC:ODBC bridge

The Driver Manager is class that belongs to the java.sql package.

Java Database Connectivity

Using Javas Driver Manager to connect to a database:
The Java Driver Manager The ODBC System DSN The Oracle database & Its tables

Creates a connection object which communicates with the ODBC driver and in turn spawns a result set object to hold the record set returned by the query made to the database table.

The Result Set Object This holds the records retrieved from the Oracle database table Data from this result set object can be bound to controls on a java form, i.e., the UI.

The Driver Manager

Locate a driver for a particular database Process JDBC initialization calls Provides entry points to JDBC functions for each specific driver Perform parameter and sequence validation for JDBC calls

The Driver Manager class

Acts as an interface between the UI and the ODBC driver Provides a set of inbuilt methods for managing database driver The getConnection() method of the DriverManager class attempts to create a connection to the specified database by invoking the JDBC:ODBC bridge and accepting the name of the system DSN as an argument. The system DSN knows where the Oracle database is. If successful, the getConnection() method spawns a Connection object, which represents a physical connection to the database. Once a physical connection with the database is established, initialization of sql queries that will be fired against the database is done. The data (records) retrived from the database table will be held in a ResultSet object. Inbuilt methods of the ResultSet facilitates navidation through the records of the ResultSet.

The java.sql package

The java.sql package contains various interfaces and classes used by the JDBC API. DriverManager class: Some methods used are
getConnection(JDBC:ODBC:name of the DSN, username, password) Connection interface: A connection object represents a connection with a database.
Within this session SQL statements can be executed, returning resultsets. Some methods of connection object are: void close() : releases all databse and JDBC resources Statement CreateStatement() : returns a new statement object that can be used to execute SQL statements.

Statement Interface: Statement object execute SQL statements that are static and obtain
results following their execution. Results are in the form of ResultSet object ResultSet.executeQuery(String SQL_statement): returns a single ResultSet object. Int executeUpdate(String SQL_statement) : this method executes SQL UPDATE, DELETE OR INSERT statements. A row count is returned by these statements.

The java.sql package

Prepared statement interface The interface Prepared statement extends the Statement interface. If the application requires multiple executions of a particular sql statement, it is pre-compiled and stored in a PreparedStatement object. This object can be used many times to execute the statement efficiently. Some of its methods are:
executeQuery() executeUpdate()

The java.sql package

ResultSet interface
The data generated on execution of a SQL statement is stored in and can be accessed from a ResultSet object. It watches a single row of data at a time. Some of the methods are:
void close(): releases ResultSet resources and JDBC resources immediately void getString(): gets the value of a column in the current row as a Java String next(): The ResultSet pointer is initially positioned before the first row, the first call to next makes the first row the current row and so on..

ResultSetMetaData interface
The ResultSetMetaData object returned by the getMetaData() constructor provides access to information which indicates the number, type and properties of the ResultSet columns. Some of its methods are:
getColumnCount() : returns no. of columns in the ResultSet String getColumnName(int) : returns the name of the column getTableName() : returns the name of the table

Connecting to Remote Database

Choosing an appropriate driver:
Java program code is used to force a particular database driver to be loaded. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Creating a connection using the DriverManager class:

Connection conn; String url = "jdbc:odbc:java"; //java is the data source name // loading the driver by passing it to 'java.lang.class' forName() method Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); // creating a connection object by passing the name of the 32bit ODBC driver conn = DriverManager.getConnection(url, "saurav", "saurav"); Performing database queries and updates: //creating a statement object Statement stmt = conn.createStatement();

ResultSet object will be created when the SQL statement is executed by the DBMS
String str = "select * from student where r_no = '" + t1.getText() + "'"; ResultSet rset = stmt.executeQuery(str);

Connecting to Remote Database

Inserting, updating, deleting
str = "insert into fac values('" + t1.getText() + "','" + t2.getText() + "'," + t3.getText() + ")"; stmt.execute(str); Also executeUpdate() method can be used which returns an int that holds the number of rows updated. Statement stmt = conn.createStatement(); int rows = executeUpdate(Update Employee set name = '" + t2.getText() + "', age =" + t3.getText() + " where r_no = '" + t1.getText() + "'"); conn.close();

Navigating through multiple rows retrieved from a database

str = "select * from sub where sub_id = '" + t1.getText() + "'"; rset = stmt.executeQuery(str); while ( ()) { t2.setText(rset.getString(2)); t3.setText(rset.getString(3)); System.out.println("Data found ..."); t4.setText(str); stmt.close(); conn.close(); }