0% found this document useful (0 votes)
4 views12 pages

Unit 4 Java Notes

The document covers GUI programming in Java using AWT, including the class hierarchy, MVC architecture, and applet basics. It explains event handling through the Delegation Event Model, detailing event classes, sources, and listener interfaces. Additionally, it discusses handling mouse and keyboard events, along with the use of adapter classes to simplify event handling code.

Uploaded by

nishitamarri123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

Unit 4 Java Notes

The document covers GUI programming in Java using AWT, including the class hierarchy, MVC architecture, and applet basics. It explains event handling through the Delegation Event Model, detailing event classes, sources, and listener interfaces. Additionally, it discusses handling mouse and keyboard events, along with the use of adapter classes to simplify event handling code.

Uploaded by

nishitamarri123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

UNIT-IV

GUI Programming with java: The AWT class hierarchy, MVC architecture, Applet Revisited:
Basics, architecture and skeleton, simple applet program.
Event Handling: Delegation Event Model, Event Classes, Source of Events, Event Listener
[Link] mouse and keyboard events, Adapter classes.
Database Programming using JDBC: Introduction to JDBC, JDBC Drivers & Architecture, CURD
operation Using JDBC, Connecting to non-conventional Databases.
Course Objective: Use Collection framework, AWT and event handling to solve real world
problems.
Course Outcome: Understand File, Streams, Input and Output Handling in java.

THE AWT CLASS HIERARCHY

Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT,
there are classes for each component as shown in above diagram. In order to place every component
in a particular position on a screen, we need to add them to a container.

Container
The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extend Container class are known as container such as Frame, Dialog and
Panel.
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog

1
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Window
The window is the container that has no borders and menu bars. You must use frame, dialog or
another window for creating a window. We need to create an instance of Window class to create
this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have
other components like button, text field, scrollbar etc. Frame is most widely used container while
developing an AWT application.
Dialog
A Dialog window is an independent sub window meant to carry temporary notice apart from the
main Swing Application Window. Most Dialogs present an error message or warning to a user,
but Dialogs can present images, directory trees, or just about anything compatible with the main
Swing Application that manages them.
Example:
// importing Java AWT class
import [Link].*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");
// setting button position on screen
[Link](30,100,80,30);

// adding button into frame


add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}
// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample1 f = new AWTExample1();
} }

2
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

MVC ARCHITECTURE
The Model-View-Controller (MVC) is a well-known design pattern in the web development
field. It is way to organize our code. It specifies that a program or application shall consist of
data model, presentation information and control information. The MVC pattern needs all these
components to be separated as different objects.
The MVC pattern architecture consists of three layers:
Model: It represents the business layer of application. It is an object to carry the data that can
also contain the logic to update controller if data is changed.
View: It represents the presentation layer of application. It is used to visualize the data that the
model contains.
Controller: It works on both the model and view. It is used to manage the flow of application,
i.e. data flow in the model object and to update the view whenever data is changed.

The advantages of MVC architecture are as follows:

 MVC has the feature of scalability that in turn helps the growth of application.
 The components are easy to maintain because there is less dependency.
 A model can be reused by multiple views that provides reusability of code.
 The developers can work with the three layers (Model, View, and Controller)
simultaneously.
 Using MVC, the application becomes more understandable.
 Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
 The extending and testing of application is easier.
Implementation of MVC using Java
To implement MVC pattern in Java, we are required to create the following three classes.
 Employee Class, will act as model layer
 EmployeeView Class, will act as a view layer
 EmployeeContoller Class, will act a controller layer

3
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

Applet Basics:
Applet It's a kind of Java Program. It generally runs in support of Java of Web Inside the
browser. Because it has a complete Java API support, So Applet It is a fully functional Java
Applications .
The following are applet dependent Java Applications:
 Java in Applet Class inherits [Link] class.
 Applet Class has no definition main(), So one Applet The program does not call main()
method .
 Applet Designed to be embedded in a HTML page.
 When a user browses a page that contains Applet of HTML page, Applet The code is
downloaded to the user's machine.
 To view a Applet need JVM. JVM It can be Web A plug-in for the browser, Or a
separate runtime environment.
 On the users machine JVM Create a Applet Class, And call Applet Various methods in
the life cycle process.
 Applets have Web Strict security rules enforced by browsers, Applet the security
mechanism is called sandbox security.
 Applet other classes you need can use Java file (JAR) Download it as a file

APPLET ARCHITECTURE AND SKELETON

Architecture of applet is quite different than the standalone programs. Applet uses GUI elements
for performing various actions from user.

Skeleton of an Applet
Applet in Java Programming extends the Applet class. An applet uses features of AWT. In an
applet program basic methods are overwritten. These methods are init(), start(), stop(), paint()
and destroy().
There are five methods of an applet life cycle, and they are:
init(): The init() method is the first method to run that initializes the applet. It can be invoked
only once at the time of initialization. The web browser creates the initialized objects, i.e., the
web browser (after checking the security settings) runs the init() method within the applet.
start(): The start() method contains the actual code of the applet and starts the applet. It is
invoked immediately after the init() method is invoked. Every time the browser is loaded or

4
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
refreshed, the start() method is invoked. It is also invoked whenever the applet is maximized,

restored, or moving from one tab to another in the browser. It is in an inactive state until the
init() method is invoked.
stop(): The stop() method stops the execution of the applet. The stop () method is invoked
whenever the applet is stopped, minimized, or moving from one tab to another in the browser,
the stop() method is invoked. When we go back to that page, the start() method is invoked again.
destroy(): The destroy() method destroys the applet after its work is done. It is invoked when the
applet window is closed or when the tab containing the webpage is closed. It removes the applet
object from memory and is executed only once. We cannot start the applet once it is destroyed.
paint(): The paint() method belongs to the Graphics class in Java. It is used to draw shapes like
circle, square, trapezium, etc., in the applet. It is executed after the start() method and when the
browser or applet windows are resized.

SIMPLE APPLET PROGRAM


import [Link].*;
import [Link].*;
public class Skeleton extends Applet
{
public void init(){ }
public void start(){ }
public void paint(Graphics gs)
{[Link]("Hello and welcome to this applet window!", 20,45); }
public void stop(){ }
public void destroy(){ }
}

DELEGATION EVENT MODEL


The delegation event model, which defines standard and consistent mechanisms to generate and
process events. Its concept is quite simple: a source generates an event and sends it to one or
more listeners. In this scheme, the listener simply waits until it receives an event. Once received,
the listener processes the event and then returns. The advantage of this design is that the
application logic that processes events is cleanly separated from the user interface logic that
generates those events.
In the delegation event model, listeners must register with a source in order to receive an event
notification. This provides an important benefit: notifications are sent only to listeners that want
to receive them.
Events:
In the delegation model, an event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a graphical user
interface. Some of the activities that cause events to be generated are pressing a button, entering
a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user
operations could also be cited as examples.
Events may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a software
or hardware failure occurs, or an operation is completed. You are free to define events that are
appropriate for your application.
Event Sources:
A source is an object that generates an event. This occurs when the internal state of that object

5
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
changes in some way. Sources may generate more than one type of event. A source must register

listeners in order for the listeners to receive notifications about a specific type of event. Each
type of event has its own registration method. Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener.
A source must also provide a method that allows a listener to unregister an interest in a specific
type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener.
Event Listeners:
A listener is an object that is notified when an event occurs. It has two major [Link],
it must have been registered with one or more sources to receive notifications about specific
types of events. Second, it must implement methods to receive and process these
[Link] methods that receive and process events are defined in a set of interfaces found
in [Link].
EVENT CLASSES, SOURCES OF EVENTS, EVENT LISTENER INTERFACES

ActionEvent indicates
that a component-
1 ActionEvent ActionListener actionPerformed() defined action occurred.

Adjustment events occur


by an adjustable object
2 AdjustmentEvent AdjustmentListener adjustmentValueChanged() like a scrollbar.

componentResized(), An event occurs when a


componentMoved(), component moved,
componentShown(),comp changed its visibility or
3 ComponentEvent ComponentListener onentHidden() the size changed.

The event is fired when a


component is added or
componentRemoved(),co removed from a
4 ContainerEvent ContainerListener mponentAdded() container.

Focus events include


focus, focusout, focusin,
5 FocusEvent FocusListener focusLost(),focusGained() and blur.

Item event occurs when


6 ItemEvent ItemListener itemStateChanged() an item is selected.

keyPressed(), A key event occurs when


keyReleased(), the user presses a key on
7 KeyEvent KeyListener keyTyped() the keyboard.

mouseClicked(),
mousePressed(), A mouse event occurs
MouseListener mouseEntered(), when the user interacts
8 MouseEvent MouseMotionListener mouseExited() with the mouse.

6
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
mouseReleased()

MouseWheelEvent occurs
when the mouse wheel
9 MouseWheelEvent MouseWheelListener mouseWheelMoved() rotates in a component.

TextEvent occurs when


10 TextEvent TextListener textChanged() an object's text change.

windowActivated(),
windowDeactivated(),
windowOpened(),
windowClosed(),
windowClosing(), Window events occur
windowIconfied(),windo when a window's status is
11 WindowEvent WindowListener wDeiconified() changed.

HANDLING MOUSE EVENTS


The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in [Link] package. It has five
methods.
Example:
import [Link].*;
import [Link].*;
public class MouseListenerExample2 extends Frame implements MouseListener{
MouseListenerExample2(){
addMouseListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
[Link]([Link]);
[Link]([Link](),[Link](),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args) {
new MouseListenerExample2();
} }

HANDLING KEYBOARD EVENTS


1. The program uses the interfaces KeyListener and ActionListener of the [Link] package.
a) The KeyListener interface has three member methods :
i) public void keyReleased(KeyEvent): This method gives the Unicode of the key released and

7
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
its character equivalent if the key pressed is a letter.
ii) public void keyPressed(KeyEvent): This method gives the Unicode of the key pressed and its

character equivalent if the key pressed is a letter.


iii) public void keyTyped(KeyEvent): This method gives the character equivalent of the key
pressed provided it is a valid character.

Example:
import [Link].*;
import [Link].*;
public class FrameKLDemo extends Frame implements KeyListener
{
TextField tf;
public FrameKLDemo()
{
add(tf = new TextField(), "South");
[Link](new Font("Monospaced", [Link], 18));

addKeyListener(this);
setFocusable(true);
setSize(300,300);
setVisible(true);
} // override the 3 abstract methods of KeyListener
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e)
{
char ch = [Link]();
[Link]("You typed " + ch + " letter");
}
public static void main(String snrao[])
{ new FrameKLDemo(); } }

ADAPTER CLASSES
ava adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
Uses of Adapter classes:
 It assists the unrelated classes to work combinedly.
 It provides ways to use classes in different ways.
 It increases the transparency of classes.
 It provides a way to include related patterns in the class.
 It provides a pluggable kit for developing an application.
 It increases the reusability of the class.

The adapter classes are found in [Link], [Link] and [Link] packages.
The Adapter classes with their corresponding listener interfaces are given below.

8
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

SNo Adapter class Listener interface

1 WindowAdapter WindowListener

2 KeyAdapter KeyListener

3 MouseAdapter MouseListener

4 MouseMotionAdapter MouseMotionListener

5 FocusAdapter FocusListener

6 ComponentAdapter ComponentListener

7 ContainerAdapter ContainerListener

8 HierarchyBoundsAdapter HierarchyBoundsListener

Example:
import [Link].*;
import [Link].*;
public class AdapterExample {
// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating a frame with the title
f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
[Link] (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
[Link](); }});
// setting the size, layout and
[Link] (400, 400);
[Link] (null);
[Link] (true); }
// main method
public static void main(String[] args) {
new AdapterExample();
}}

INTRODUCTION TO JDBC
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the
database. It is a specification from Sun microsystems that provides a standard abstraction(API or
Protocol) for java applications to communicate with various databases.
Definition of JDBC(Java Database Connectivity)
JDBC is an API(Application programming interface) used in java programming to interact with
databases. The classes and interfaces of JDBC allow the application to send requests made by
users to the specified database.

9
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with databases to
store application-specific information. So, interacting with a database requires efficient database
connectivity, which can be achieved by using the ODBC(Open database connectivity) driver.
This driver is used with JDBC to interact or communicate with various kinds of databases such as
Oracle, MS Access, Mysql, and SQL server database.
JDBC DRIVERS & ARCHITECTURE
JDBC drivers are client-side adapters that convert requests from Java programs to a protocol that
the DBMS can understand. There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

10
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.

CURD OPERATION USING JDBC


CRUD - Create, Retrieve, Update and Delete using JDBC (Java Database Connectivity) API.
These CRUD operations are equivalent to the INSERT, SELECT, UPDATE and DELETE
statements in SQL language. Although the target database system is MySQL, but the same
technique can be applied for other database systems as well because the query syntax used is
standard SQL which is supported by all relational database systems.
Example:
String sql = "SELECT * FROM Users";
Statement statement = [Link]();
ResultSet result = [Link](sql);
int count = 0;
while ([Link]())
{ String name = [Link](2);
String pass = [Link](3);
String fullname = [Link]("fullname");
String email = [Link]("email");
String output = "User #%d: %s - %s - %s - %s";
[Link]([Link](output, ++count, name, pass, fullname, email));
}

CONNECTING TO NON-CONVENTIONAL DATABASES

To connect java application with the non-conventional databases, we need to follow 5 following
steps. In this example, we are using Oracle 10g as the database. So we need to know following
information for the oracle database:
1. Driver class: The driver class for the oracle database is [Link].
2. Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the
driver, localhost is the server name on which oracle is running, we may also use IP address,

11
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
1521 is the port number and XE is the Oracle service name. You may get all these
information from the [Link] file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database.
Example:
import [Link].*;
class MysqlCon{
public static void main(String args[]){
try{ [Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]()) { [Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}catch(Exception e){ [Link](e);}
} }

END OF UNIT - IV

12

You might also like