0% found this document useful (0 votes)
12 views40 pages

Java Applets and Event Handling Guide

Uploaded by

hegdeshravya4
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)
12 views40 pages

Java Applets and Event Handling Guide

Uploaded by

hegdeshravya4
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

Unit – IV

Event Handling, AWT and Swing


What is Applet?
• An applet is a Java program that can be embedded into a web page.
• It runs inside the web browser and works at client side.
• An applet is embedded in an HTML page using the APPLET tag
• Applets are used to make the website more dynamic and entertaining.
• All applets are sub-classes (either directly or indirectly)
of [Link] class.
• Applets are not stand-alone programs. Instead, they run within either a web
browser or an applet viewer. JDK provides a standard applet viewer tool
called applet viewer.
• In general, execution of an applet does not begin at main() method.
• Output of an applet window is not performed by [Link]().
Rather it is handled with various AWT methods, such as drawString().
Life cycle of an applet:
 It is important to understand the order in which the various methods shown
in the above image are called. When an applet begins, the following
methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
 When an applet is terminated, the following sequence of method calls takes
place:
1. stop( )
2. destroy( )
1. init( ) : The init( ) method is the first method to be called. This is where
you should initialize variables. This method is called only
once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart
an applet after it has been stopped
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s
output must be redrawn.
paint(Graphics g) -is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page
5. destroy( ) : The destroy( ) method is called when the environment
determines that your applet needs to be removed completely from
memory
Simple Applet program
//[Link]
import [Link];
import [Link];
public class First extends Applet{
public void paint(Graphics g){
[Link]("welcome to applet",150,150);
}
}
/*
<applet code="First" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
C:/> Javac [Link]
C:/> appletviewer [Link]
Applet runtime architecture

 The database server is connected to the JDBC driver, which is connected


to the applet.
 The applet is also connected to a browser, which is connected to a web
server that communicates with the database.
 The database server is connected to the JDBC driver, which is connected
to the applet.
 The applet is also connected to a browser, which is connected to a web
server that communicates with the database.
Applet Display methods
 Applets are displayed in a window and they use the AWT to perform input
and output functions.
 To output a string to an applet, use drawString( ), which is a member of
the Graphics class.
 Typically, it is called from within either update() or paint( ). It has the
following general form:
void drawString(String message, int x, int y)
The example below shows a simple applet to change the color of the foreground
and background.
import [Link].*;
import [Link].*;
/* <applet code="Applet_Prog" width=500 height=550> </applet>*/
public class Applet_Prog extends Applet
{
public void paint (Graphics g)
{
setBackground([Link]);
setForeground([Link]);
[Link]("Using Colors in An Applet" , 100,250);
}
}
Repaint method()
 The repaint () method causes the AWT runtime system to execute the
update () method of the Component class which clears the window with
the background color of the applet and then calls the paint () method.
 For example: Suppose you want to display the current x and y coordinates
of the location where the mouse button is clicked in the applet window. As
the applet needs to update information displayed in its window (i.e. redraw
the window)
 each time the mouse is being clicked so this is possible with the use of
repaint () method. To sum up, the repaint() method is invoked to refresh
the viewing area i.e. you call it when you have new things to display.
import [Link].*;
import [Link];
import [Link].*;
/*<applet code="[Link]" width="350" height="150">
</applet>*/
public class RepaintJavaExample extends Applet implements
MouseListener
{
private int mouseX, mouseY;
private boolean mouseclicked = false;
public void init()
{
setBackground([Link]);
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
mouseX = [Link]();
mouseY=[Link]();
mouseclicked = true;
repaint();
}
public void mouseEntered(MouseEvent e){};
public void mousePressed(MouseEvent e){};
public void mouseReleased(MouseEvent e){};
public void mouseExited(MouseEvent e){};
public void paint( Graphics g )
{
String str;
[Link]([Link]);
if (mouseclicked)
{
str = "X="+ mouseX + "," + "Y="+ mouseY ;
[Link](str,mouseX,mouseY);
mouseclicked = false;
}
}
}
status window in applet
 The status window is a good place to give the user feedback about what is
occurring in the applet, suggest options, or possibly report some types of
errors.
 The status window also makes an excellent debugging aid, because it gives
you an easy way to output information about your applet.
The following applet demonstrates showStatus( ):
// Using the Status Window.
import [Link].*;
import [Link].*; /*
<applet code="StatusWindow" width=300 height=50> </applet> */
public class StatusWindow extends Applet { public void init() {
setBackground([Link]);
}
// Display msg in applet window.
public void paint(Graphics g) {
[Link]("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
} }
EVENT HANDLING
Event Handling Mechanism
 Any program that uses GUI (graphical user interface) such as Java
application written for windows, is event driven.
 Event describes the change in state of any object.
For Example : Pressing a button, Entering a character in Textbox,
Clicking or Dragging a mouse, etc.
 The [Link] package can be used to provide various event
classes.
Classification of Events
• Foreground Events
• Background Events
1. Foreground Events
 Foreground events are the events that require user interaction to generate,
i.e., foreground events are generated due to interaction by the user on
components in Graphic User Interface (GUI).
 Interactions are nothing but clicking on a button, scrolling the scroll bar,
cursor moments, etc.
2. Background Events
 Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.
Delegation Event Model
 It is a mechanism to control the events and to decide what should
happen after an event occur.
 To handle the events, Java follows the Delegation Event model.
Delegation Event model
• It has Sources and Listeners.

• Source: Events are generated from the source. There are various sources
like buttons, checkboxes, list, menu-item, choice, scrollbar, text
components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible for
handling events.
 To perform Event Handling, we need to register the source with the listener.

Registering the Source With Listener


Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register..
Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a component-


ActionEvent ActionListener defined action occurred like a button click
or selecting an item from the menu-item list.

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.

An event that indicates that a component


ComponentEvent ComponentListener moved, the size changed or changed its
visibility.

When a component is added to a container


ContainerEvent ContainerListener (or) removed from it, then this event is
generated by a container object.

These are focus-related events, which


FocusEvent FocusListener
include focus, focusin, focusout, and blur.

An event that indicates whether an item was


ItemEvent ItemListener
selected or not.
An event that occurs due to a sequence of
KeyEvent KeyListener
keypresses on the keyboard.

The events that occur due to the user


MouseListener &
MouseEvent interaction with the mouse (Pointing
MouseMotionListener
Device).

An event that specifies that the mouse


MouseWheelEvent MouseWheelListener
wheel was rotated in a component.

An event that occurs when an object’s


TextEvent TextListener
text changes.

An event which indicates whether a


WindowEvent WindowListener
window has changed its status or not.

Event Listener Interface

Listener Interface Methods

ActionListener • actionPerformed()

AdjustmentListener • adjustmentValueChanged()

• componentResized()
• componentShown()
ComponentListener
• componentMoved()
• componentHidden()

• componentAdded()
ContainerListener
• componentRemoved()
• focusGained()
FocusListener
• focusLost()

ItemListener • itemStateChanged()

• keyTyped()
KeyListener • keyPressed()
• keyReleased()

• mousePressed()
• mouseClicked()
MouseListener • mouseEntered()
• mouseExited()
• mouseReleased()

• mouseMoved()
MouseMotionListener
• mouseDragged()

MouseWheelListener • mouseWheelMoved()

TextListener • textChanged()

• windowActivated()
• windowDeactivated()
• windowOpened()
WindowListener • windowClosed()
• windowClosing()
• windowIconified()
• windowDeiconified()

Mouse Events in java


 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.
 Methods of MouseListener interface
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
Java MouseListener Example
import [Link].*;
import [Link].*;
public class MouseListenerExample extends Frame implements
MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
[Link](20,50,100,20);
add(l);
setSize(300,300);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

Keyboard events
 The Java KeyListener is notified whenever you change the state of
key.
 It is notified against KeyEvent.
 The KeyListener interface is found in [Link] package, and it has
three methods.

Sr. Method name Description


no.

1. public abstract void keyPressed It is invoked when a key has been


(KeyEvent e); pressed.

2. public abstract void It is invoked when a key has been


keyReleased (KeyEvent e); released.

3. public abstract void keyTyped It is invoked when a key has been


(KeyEvent e); typed.

JAVA AWT

Abstract Window Tool Kit


• Java AWT is an API that contains large number of classes and methods to
create and manage graphical user interface ( GUI ) applications.
• The AWT was designed to provide a common set of tools for GUI design
that could work on a variety of platforms.
• AWT was Java’s first GUI Framework.
• AWT is the foundation upon which Swing is made i.e Swing is a improved
GUI API that extends the AWT.
• Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system.
• AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS)
• Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system.
• The [Link] package provides classes for AWT API such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT 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 extends Container class are known as container such as
Frame, Dialog and Panel.
• It is basically a screen where the components are placed at their specific
locations.
• Thus it contains and controls the layout of components.

Types of containers:
There are four types of containers in Java AWT:
• Window
• Panel
• Frame
• Dialog
Window
• The window is the container that have 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.
• Frame is a subclass of Window and have resizing canvas.
The Dialog control
• The Dialog control represents a top level window with a border and a title
used to take some form of input from the user.
• It inherits the Window class.
• Unlike Frame, it doesn't have maximize and minimize buttons.
• Frame and Dialog both inherits Window class.
• Frame has maximize and minimize buttons but Dialog doesn't have.
Creating a Frame
There are two ways to create a Frame. They are,
• By Instantiating Frame class
• By extending Frame class

Points to Remember:
• While creating a frame (either by instantiating or extending Frame class),
Following two attributes are must for visibility of the frame:
• setSize(int width, int height);
• setVisible(true);
• When you create other components like Buttons, TextFields, etc. Then you
need to add it to the frame by using the method - add(Component's
Object);
• You can add the following method also for resizing the frame
- setResizable(true);
By Instantiating Frame class

By extending Frame class

Understanding Layout Managers


• The layout manager automatically positions all the components within the
container. If we do not use layout manager then also the components are
positioned by the default layout manager.
• Each Container object has a layout manager associated with it.
• A layout manager is an instance of any class that implements the
LayoutManagerinterface.
• The layout manager is set by the setLayout( ) method.
• If no call to setLayout( ) is made,then the default layout manager is used.
• Whenever a container is resized (or sized for the first time), the layout
manager is used to position each of the components within it.
• The setLayout( ) method has the following general form:
• void setLayout(LayoutManager layoutObj)

FlowLayout
• It is the default layout manager.
• FlowLayout implements a simple layout style, which is similar to how
words flow in a text editor.
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• These values specify left, center, right, leading edge, and trailing edge
alignment, respectively
BorderLayout
• The BorderLayout class implements a common layout style for top-level
windows.
• It has four narrow, fixed-width components at the edges and one large area
in the center.
• The four sides are referred to as north, south, east, and west. The middle
area is called the center.
• BorderLayout defines the following constants that specify the regions:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]

AWT Control Fundamentals


❑ The AWT supports the following types of controls:
❑ These controls are subclasses of Component.
• Labels
• Buttons
• Check boxes
• Check box groups
• Choice control
• Lists
• Scroll bar
• Text field
• Text area
Adding and Removing Controls
• In order to include a control in a window, we must add it to the window.
• So, we must first create an instance of the desired control and then add it
to a window by calling add( ), which is defined by Container.
• Component add(Component compObj)
• Once a control has been added, it will automatically be visible whenever
its parent window is displayed.
• Sometimes we will want to remove a control from a window when the
control is no longer needed.
• For doing this, call remove( ).
• This method is also defined by Container.
• It has this general form: void remove(Component obj) Here, obj is a
reference to the control that we want to remove.
• We can remove all controls by calling removeAll( )
Label
• A label is a user for placing text inside the container.
• A label is used only for inputting text.
• The label does not imply that the text can be altered or it can be used as a
button which can be further worked upon.
o Label n=new Label("Name:",[Link]);
Button
• This command generates a button in the User Interface.
• Clicking on the button would move the command to another page or
another web server which is used to show several other outputs in the user
interface page.
a1=new Button("submit");
a2=new Button("cancel");
Check Boxes
• A check box is a control that is used to turn an option on or off. It consists
of a small box that can either contain a check mark or not.
• There is a label associated with each check box that describes what option
the box represents.
• We change the state of a check box by clicking on it. Check boxes can be
used individually or as part of a group.
• Check boxes are objects of the Checkbox class
Checkbox checkbox1 = new Checkbox("Hello World");
Checkbox Group
• It is possible to create a set of mutually exclusive check boxes in which
one and only one check box in the group can be checked at any one time.
• These are often called radio buttons.
• For creating a set of mutually exclusive check boxes, we must first define
the group to which they will belong and then specify that group when we
construct the check boxes.
• Check box groups are objects of type CheckBoxGroup.
CheckboxGroup cb = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("Hello", cb, true);
[Link] (100,100, 50,50);
Managing Scroll Bars
• Scroll bars are used to select continuous values between a specified
minimum and maximum. Scroll bars may be oriented horizontally or
vertically.
• Each end has an arrow that you can click to move the current value of the
scroll bar one unit in the direction of the arrow.
Scrollbar s=new Scrollbar();
[Link](100,100, 50,100);
TextField
• The TextField class implements a single-line text-entry area, usually
called an edit control.
• Text fields allow the user to enter strings and to edit the text using the
arrow keys, cut and paste keys, and mouse selections.
na=new TextField(“my name”);
TextArea
• Sometimes a single line of text input is not enough for a given task. To
handle these situations, the AWT includes a simple multiline editor called
TextArea.
TextArea area=new TextArea("Welcome to the universe");
[Link](10,30, 300,300);
Choice Controls
• The Choice class is used to create a pop -up list of items from which the
user may choose. Thus, a Choice control is a form of menu.
• When inactive, a Choice component takes up only enough space to show
the currently selected item. When the user clicks on it, the whole list of
choices pops up, and a new selection can be made.
Choice c=new Choice();
[Link](100,100, 75,75);
[Link]("Subject 1");
[Link]("Subject 2");
[Link]("Subject 3");
Lists
• The List class provides a compact, multiple-choice, scrolling selection
list.
• Unlike the Choice object, which shows only the single selected item in
the menu, a List object can be constructed to show any number of choices
in the visible Window.
• It can also be created to allow multiple selections.
Menu Bars and Menus
• A top-level window can have a menu bar associated with it.
• A menu bar displays a list of top-level menu choices.
• Each choice is associated with a drop-down menu.
• This concept is implemented in the AWT by the following classes:
MenuBar, Menu,and MenuItem.
• In general, a menu bar contains one or more Menu objects. Each Menu
object contains a list of MenuItem objects.
• Each MenuItem object represents something that can be selected by the
user.
• Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can
be created.
• It is also possible to include checkable menu items.
• These are menu options of type CheckboxMenuItem and will have a check
mark next to them when they are selected.
• Creating Menubar
▪ MenuBar mb=new MenuBar();
• Menu a creation
▪ Menu mnu1=new Menu("BCA");
▪ Menu mnu2=new Menu("BBA");
• sm1 and sm2 will be treated as submenus
• Menu sm1=new Menu("Semester");
• Menu sm2=new Menu("Year");
• adding items and submenus to menu
• [Link](sm1);
• [Link](sm2);

• //adding items to submenu


▪ [Link](i1);
▪ [Link](i2);
▪ [Link](i3);
• //adding menu to menubar
▪ [Link](mnu1);
▪ [Link](mnu2);
• Creating menu items
MenuItem i1,i2,i3;
i1=new MenuItem("I");
i2=new MenuItem("II");
i3=new MenuItem("2023");
Dialog Boxes
• Dialog boxes are primarily used to obtain user input and are often child
windows of a top-level window.
• Dialog boxes don’t have menu bars, but in other respects, they function
like frame windows. (You can add controls to them, for example, in the
same way that you add controls to a frame window.)
• When a modal dialog box is active, all input is directed to it until it is
closed.
• This means that you cannot access other parts of your program until you
have closed the dialog box.
• When a modeless dialog box is active, input focus can be directed to
another window in your program.
• Thus, other parts of your program remain active and accessible. In the
AWT, dialog boxes are of type Dialog
FileDialog
❑ Java provides a built-in dialog box that lets the user specify a file.
❑ To create a file dialog box, instantiate an object of type FileDialog. This
causes a file dialog box to be displayed.
❑ Usually, this is the standard file dialog box provided by the operating
system.

Handling Events by Extending AWT Components


❑ Handling events by extending AWT components.
❑ The delegation event model was introduced in Event handling, and all of
the programs in this book so far have used that design. But Java also
allows you to handle events by subclassing AWT components.
❑ Doing so allows you to handle events in much the same way as they were
handled under the original 1.0 version of Java. Of course, this technique
is discouraged, because it has the same disadvantages of the Java 1.0
event model, the main one being inefficiency.
❑ To extend an AWT component, you must call the enableEvents( ) method
of Component. Its general form is shown here:
SWING
• Java Swing is a popular and powerful Graphical User Interface (GUI)
toolkit that is used for developing desktop applications.
• It is a part of the Java Foundation Classes (JFC) and provides a rich set of
components and layout managers for creating a variety of GUIs.
• Java Swing is platform-independent and can be used on any operating
system that supports Java.
• It provides a set of lightweight components that are not only easy to use
but also customizable.
• Some of the commonly used components in Swing are buttons, text fields,
labels, menus, and many more.
• It also provides a robust event-handling mechanism that allows developers
to handle events generated by the graphical components.
• Some of the commonly used layout managers in Java Swing are
BorderLayout, FlowLayout, GridLayout, CardLayout, and BoxLayout.

Features of Java Swing


❑ Platform Independence: Platform independence is one of Java Swing’s
most remarkable features. It can run on any platform that supports Java.
Thus, Swing-based applications can run on Windows, Mac, Linux, or any
other Java-compatible operating system.
❑ Lightweight Components: Java Swing provides a set of lightweight
components that are easy to use and customizable. These components are
designed to consume less memory and use less processing power, making
Swing-based applications run efficiently.
❑ Layout Managers: Java Swing provides a set of layout managers that can
be used to organize the graphical components in a GUI. These layout
managers enable developers to create flexible and responsive GUIs that
adapt to different screen sizes and resolutions.
❑ Robust Event Handling Mechanism: Java Swing provides a robust event
handling mechanism that allows developers to handle events generated by
the graphical components. Developers can register event listeners to detect
and respond to user interactions with the GUI.
❑ Pluggable Look and Feel: Java Swing provides a pluggable look and feels
that allows developers to customize the appearance of the GUI according
to the user’s preferences. Developers can choose from several pre-built
looks and feel themes or create their own custom themes.
The Model-View-Controller Architecture:
• Swing uses the model-view-controller architecture (MVC) as the
fundamental design behind each of its components. Essentially, MVC
breaks GUI components into three elements.
• Each of these elements plays a crucial role in how the component behaves.
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.

Advantages of MVC Architecture


• 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.

Swing Applets
❑ So far, we have created the applets based on AWT(Abstract Window
Toolkit) by extending the Applet class of the awt package.
❑ We can even create applets based on the Swing package. In order to create
such applets, we must extend JApplet class of the swing package
❑ JApplet is a top-level container class and you should never draw on it
directly, instead you should draw on the component class like JPanel and
then add this JPanel to the JApplet

Creating a swing applet


• In the upcoming code, first, we have created a swing applet by
extending JApplet class and we have added a JPanel to it.
• Next, we have created a class B, which has extended JPanel class of Swing
package and have also implemented ActionListener interace to listen to the
button click event generated when buttons added to JPanel are clicked.

You might also like