0% found this document useful (0 votes)
3 views28 pages

UNIT-IV Event Handling

AWT (Abstract Window Toolkit) is a platform-dependent API for creating GUI in Java, which uses native OS components leading to different appearances across platforms. It includes heavy-weight components and has limitations such as a fixed look and feel, prompting the development of Swing, a more flexible and lightweight alternative. AWT provides various components like buttons, text fields, and layout managers, allowing developers to create interactive applications.
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)
3 views28 pages

UNIT-IV Event Handling

AWT (Abstract Window Toolkit) is a platform-dependent API for creating GUI in Java, which uses native OS components leading to different appearances across platforms. It includes heavy-weight components and has limitations such as a fixed look and feel, prompting the development of Swing, a more flexible and lightweight alternative. AWT provides various components like buttons, text fields, and layout managers, allowing developers to create interactive applications.
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
You are on page 1/ 28

UNIT-IV(AWT)

AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating Graphical User
Interface (GUI) for java programs.

Why AWT is platform dependent? Java AWT calls native platform (Operating systems) subroutine for
creating components such as textbox, checkbox, button etc. For example an AWT GUI having a button would
have a different look and feel across platforms like windows, Mac OS & Unix, this is because these platforms
have different look and feel for their native buttons and AWT directly calls their native subroutine that creates
the button. In simple, an application build on AWT would look like a windows application when it runs on
Windows, but the same application would look like a Mac application when runs on Mac OS.

AWT components are considered heavy weight because they are being generated by underlying operating
system (OS). For example if you are instantiating a text box in AWT that means you are actually asking OS to
create a text box for you.

Swing is a preferred API for window based applications because of its platform independent and light-weight
nature. Swing is built upon AWT API however it provides a look and feel unrelated to the underlying
platform. It has more powerful and flexible components than AWT. In addition to familiar components such as
buttons, check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll
panes, trees, tables, and lists. We will discuss Swing in detail in a separate tutorial.

AWT hierarchy

Java AWT Example

Components and containers

All the elements like buttons, text fields, scrollbars etc are known as components. In AWT we have classes for
each component as shown in the above diagram. To have everything placed on a screen to a particular position,
we have to add them to a container. A container is like a screen wherein we are placing components like
buttons, text fields, checkbox etc. In short a container contains and controls the layout of components. A
container itself is a component (shown in the above hierarchy diagram) thus we can add a container inside
container.
Types of containers: As explained above, a container is a place wherein we add components like text field,
button, checkbox etc. There are four types of containers available in AWT: Window, Frame, Dialog and Panel.
As shown in the hierarchy diagram above, Frame and Dialog are subclasses of Window class.

Window: An instance of the Window class has no border and no title


Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist without an associated
instance of the Frame class.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for holding components.
An instance of the Panel class provides a container to which to add components.
Frame: A frame has title, border and menu bars. It can contain several components like buttons, text fields,
scrollbars etc. This is most widely used container while developing an application in AWT.

Useful Methods of Component class


Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default false.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
o By extending Frame class (inheritance)
o By creating the object of Frame class (association)

Let's see a simple example of AWT where we are inheriting Frame class.

import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are showing
Button component on the Frame.
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Limitations of AWT:
➢ The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but
limited graphical interface.
➢ One reason for the limited nature of the AWT is that it translates its various visual components
into their corresponding, platform-specific equivalents or peers.
➢ This means that the look and feel of a component is defined by the platform, not by java.
Because the AWT components use native code resources, they are referred to as heavy weight.
➢ The use of native peers led to several problems. First, because of variations between operating
systems, a component might look, or even act, differently on different platforms.
➢ This variability threatened java’s philosophy: write once, run anywhere.
➢ Second, the look and feel of each component was fixed and could not be changed.
➢ Third, the use of heavyweight components caused some frustrating restrictions.
➢ Due to these limitations Swing came and was integrated to java.
➢ Swing is built on the AWT.
Two key Swing features are:
1. Swing components are light weight,
2. Swing supports a pluggable look and feel.

AWT GUI Component:

java.awt.Label
A java.awt.Label provides a descriptive text string. Take note that System.out.println() prints
to the system console, NOT to the graphics screen. You could use a Label to label another
component (such as text field) to provide a text description.

Constructors

// Construct a Label with the given text String, of the text alignment

public Label(String strLabel, int alignment);

// Construct a Label with the given text String


public Label(String strLabel);

public Label(); // Construct an initially empty Label

Public Methods

// Examples
public String getText();
public void setText(String strLabel);
public int getAlignment();
public void setAlignment(int alignment); // Label.LEFT, Label.RIGHT, Label.CENTER

AWT GUI Component: java.awt.Button

A java.awt.Button is a GUI component that triggers a certain programmed action upon


clicking.

Constructors
public Button(String btnLabel);
// Construct a Button with the given label
public Button();
// Construct a Button with empty label

Public Methods
public String getLabel();
// Get the label of this Button instance
public void setLabel(String btnLabel);
// Set the label of this Button instance
public void setEnable(boolean enable);
// Enable or disable this Button. Disabled Button cannot be clicked.

The getLabel() and setLabel() methods can be used to read the current label and modify the
label of a button, respectively.

Clicking a button fires a so-called ActionEvent and triggers a certain programmed action

AWT GUI Component: java.awt.TextField

A java.awt.TextField is single-line text box for users to enter texts

Constructors

public TextField(String initialText);


// Construct a TextField instance with the given initial text string.
public TextField(int columns);
// Construct a TextField instance with the number of columns.
public TextField(String initialText, int columns);
// Construct a TextField instance with the given initial text string with the number of
columns.

Public Methods

public String getText();


// Get the current text on this TextField instance
public void setText(String strText);
// Set the display text on this TextField instance
public void setEditable(boolean editable);
// Set this TextField to editable (read/write) or non-editable (read-only)

Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or
from "off" to "on".

To find out the state of a checkbox object we can use getState() that returns a true
or false value.
We can also get the label of the checkbox using getLabel() that returns a String
object.

Constructors are
Checkbox()
Creates a check box with an empty string for its label.
Checkbox(String label)
Creates a check box with the specified label.
Checkbox(String label, boolean state)
Creates a check box with the specified label and sets the specified state.

CheckboxGroup
CheckboxGroup class is used to group together a set of Checkbox. At a time only
one check box button is allowed to be in "on" state and remaining check box
button in "off" state.
Constructor
CheckboxGroup()
Creates a new instance of CheckboxGroup.
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}

List (java.awt.List)

List components objects are useful for holding a large number of data items. They
are quite similar to the Choice component, however they can allow for the multiple
selection of items. The list automatically adds a scrollbar if it is required. The list
constructor takes two arguments, the int number of items to be displayed and a
boolean to allow/disallow multiple item selection.
Figure 9.13. A List Component

List provides these constructors:


List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
To add a selection to the list, call add( ). It has the following two forms: void
add(String name) void add(String name, int index)
import java.awt.*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
List l1=new List(5);
l1.setBounds(100,100, 75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}

Choice
Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.

Constructor
Choice() :Creates a new choice menu.
import java.awt.*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceExample();
}
}
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. A scroll bar is actually a composite of several individual parts. 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. The current value of the scroll bar relative to its minimum and maximum values is indicated by the
slider box (or thumb) for the scroll bar
Scrollbar defines the following constructors:
Scrollbar( ) throws HeadlessException
Scrollbar(int style) throws HeadlessException
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
The first form creates a vertical scroll bar. The second and third forms allow you to specify the orientation of
the scroll bar. If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If style is
Scrollbar.HORIZONTAL, the scroll bar is horizontal. In the third form of the constructor, the initial value of
the scroll bar is passed in initialValue

import java.awt.*;
class ScrollbarExample{
ScrollbarExample(){
Frame f= new Frame("Scrollbar Example");
Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new ScrollbarExample();
}
}
Using a 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. Following are the constructors for TextArea: TextArea( )
throws HeadlessException TextArea(int numLines, int numChars) throws HeadlessException
TextArea(String str) throws HeadlessException TextArea(String str, int numLines, int numChars) throws
HeadlessException TextArea(String str, int numLines, int numChars, int sBars) throws HeadlessException

import java.awt.*;
public class TextAreaExample
{
TextAreaExample(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to javatpoint");
area.setBounds(10,30, 300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must
belong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the
MenuItem class.

Java AWT MenuItem and Menu Example


import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}

Understanding Layout Managers


All of the components that we have shown so far have been 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 LayoutManager interface.
The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then
the default layout manager is used
SYNTAX
void setLayout(LayoutManager layoutObj)
Java has several predefined LayoutManager classes
FlowLayout
• FlowLayout is the default layout manager.
• This is the layout manager that the preceding examples have used.
• FlowLayout implements a simple layout style, which is similar to how words flow in a text editor.

• The direction of the layout is governed by the container’s component orientation property, which, by
default, is left to right, top to bottom.

• Here are the constructors for FlowLayout:


FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five pixels of space
between each component. The second form lets you specify how each line is aligned. Valid values for
how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT

import java.awt.*;
import javax.swing.*;

public class MyFlowLayout{


JFrame f;
MyFlowLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}

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.
• Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
 The first form creates a default border layout.
 The second allows you to specify the horizontal and vertical space left between components in horz
and vert, respectively.
• BorderLayout defines the following constants that specify the regions: BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
• When adding components, you will use these constants with the following form of add( ), which is defined by
Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies where the component will be added

import java.awt.*;

class BorderLayoutExample extends Frame

{
BorderLayoutExample()

setLayout(new BorderLayout());

add(new Button("NORTH"),BorderLayout.NORTH);

add(new Button("SOUTH"),BorderLayout.SOUTH);

add(new Button("EAST"),BorderLayout.EAST);

add(new Button("WEST"),BorderLayout.WEST);

add(new Button("CENTER"),BorderLayout.CENTER);

class BorderLayoutJavaExample

public static void main(String args[])

BorderLayoutExample frame = new BorderLayoutExample();

frame.setTitle("BorderLayout in Java Example");

frame.setSize(400,150);

frame.setVisible(true);

}
GridLayout
GridLayout lays out components in a two-dimensional grid.
When you instantiate a GridLayout, you define the number of rows and columns.
The constructors supported by GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
 The first form creates a single-column grid layout.
 The second form creates a grid layout with the specified number of rows and columns.
 The third form allows you to specify the horizontal and vertical space left between components in horz
and vert, respectively. Either numRows or numColumns can be zero. Specifying numRows as zero
allows for unlimited-length columns.

import java.awt.*;

class GridLayoutExample extends Frame

GridLayoutExample()

Button[] button =new Button[12];

setLayout(new GridLayout(4,3));

for(int i=0; i<button.length;i++)

button[i]=new Button("Button "+(i+i));

add(button[i]);

class GridLayoutJavaExample

public static void main(String args[])

GridLayoutExample frame = new GridLayoutExample();

frame.setTitle("GridLayout in Java Example");

frame.setSize(400,150);

frame.setVisible(true);

}
CardLayout
 The CardLayout class is unique among the other layout managers in that it stores several different
layouts.
 Each layout can be thought of as being on a separate index card in a deck that can be shuffled so
that any card is on top at a given time.
 This can be useful for user interfaces with optional components that can be dynamically enabled
and disabled upon user input. You can prepare the other layouts and have them hidden, ready to be
activated when needed.
 CardLayout provides these two constructors:
 CardLayout( )
 CardLayout(int horz, int vert)
 The first form creates a default card layout.

 The second form allows you to specify the horizontal and vertical space left between components
in horz and vert, respectively
void add(Component panelObj, Object name)

import java.awt.*;

import java.awt.event.*;

class CardLayoutExample extends Frame implements ActionListener

CardLayout card = new CardLayout(20,20);

CardLayoutExample()

setLayout(card);

Button Btnfirst = new Button("first ");

Button BtnSecond = new Button ("Second");

Button BtnThird = new Button("Third");

add(Btnfirst,"Card1");

add(BtnSecond,"Card2");

add(BtnThird,"Card3");

Btnfirst.addActionListener(this);

BtnSecond.addActionListener (this);

BtnThird.addActionListener(this);
}

public void actionPerformed(ActionEvent e)

card.next(this);

class CardLayoutJavaExample

public static void main(String args[])

CardLayoutExample frame = new CardLayoutExample();

frame.setTitle("CardLayout in Java Example");

frame.setSize(220,150);

frame.setResizable(false);

frame.setVisible(true);

}
GridBagLayout
What makes the grid bag useful is that you can specify the relative placement of components by specifying
their positions within cells inside a grid. The key to the grid bag is that each component can be a different size,
and each row in the grid can have a different number of columns. This is why the layout is called a grid bag.
It’s a collection of small grids joined together.
GridBagLayout defines only one constructor, which is shown here:
GridBagLayout( )

Event Handling Java

What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as
result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse,
entering a character through keyboard,selecting an item from list, scrolling the page are the activities that causes an event to
happen.

Types of Event
The events can be broadly classified into two categories:
• Foreground Events - Those events which require the direct interaction of user.They are generated as consequences
of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button,
moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc.
• Background Events - Those events that require the interaction of end user are known as background events.
Operating system interrupts, hardware or softwar

What is Event Handling?


Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism
have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model
to handle the events.

The Delegation Event Model

The modern approach to handling events is based on the delegation event model. The delegation event model
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 logic that processes events is cleanly separated from the user interface logic that generates
those events.

There are three participants in event delegation model in Java;

- Event Source – the class which broadcasts the events


- Event Listeners – the classes which receive notifications of events
- Event Object – the class object which describes the event.

An event occurs (like mouse click, key press, etc) which is followed by the event is broadcasted by the event
source by invoking an agreed method on all event listeners. The event object is passed as argument to the
agreed-upon method. Later the event listeners respond as they fit, like submit a form, displaying a message /
alert etc.
The event handling Java involves four types of classes.
1. Event Sources
2. Event classes
3. Event Listeners
4. Event Adapters
1. Event Sources
Event sources are components, subclasses of java.awt.Component, capable to generate
events. The event source can be a button, TextField or a Frame etc.
2. Event classes

Almost every event source generates an event and is named by some Java class. For example,
the event generated by button is known as ActionEvent and that of Checkbox is known as
ItemEvent. All the events are listed in java.awt.event package.

3. Event Listeners

The events generated by the GUI components are handled by a special group of interfaces
known as "listeners". Note, Listener is an interface. Every component has its own listener,
say, AdjustmentListener handles the events of scrollbar Some listeners handle the events of
multiple components. For example, ActionListener handles the events of Button, TextField,
List and Menus. Listeners are from java.awt.event package.

4. Event Adapters

When a listener includes many abstract methods to override, the coding becomes heavy to the
programmer. For example, to close the frame, you override seven abstract methods of
WindowListener, in which, infact you are using only one method. To avoid this heavy
coding, the designers come with another group of classes known as "adapters". Adapters are
abstract classes defined in java.awt.event package. Every listener that has more than one
abstract method has got a corresponding adapter class
Event Listener Interfaces
• java.awt.Event package : Listener interfaces to handle events.

All the interfaces and the methods

Event Generated by Listener Interface Methods in them

Action event Pressing a button ActionListener actionPerformed()


Adjustment event Scroll bar is AdjustmentListener adjustmentValueChanged()
manipulated
Component event A component is ComponentListener componentHidden()
hidden, moved, componentMoved()
resized, or shown componentResized()
componentShown()
Container event A component is ContainerListener componentAdded()
added or removed componentRemoved()
from a container
Focus event A component gains or FocusListener focusGained()
loses focus focusLost()
Item event An item is selected or ItemListener itemStateChanged()
deselected
Key event A key is pressed, KeyListener keyPressed()
released or typed keyReleased()
keyTyped()
Mouse event Mouse button is MouseListener mouseClicked()
clicked, pressed or mouseEntered()
released. Mouse mouseExited()
pointer enters leaves a mousePressed()
component mouseReleased()
Mouse event Mouse pointer is MouseMotionListener mouseDragged()
dragged or moved mouseMoved()
Text event Text value is changed TextListener textValueChanged()
Window event A window is WindowListener windowActivated()
activated, closed, windowClosed()
deactivated, windowClosing()
deiconfied, opened, or windowDeactivated()
quit windowDeiconified()
windowIconified()
windowOpened()
Steps to handle events (Event Handling)

Step 1: Import classes from the package:

import java.awt.event.*;
Step 2: Implement the appropriate listener interfaces.
public class sample extends Applet implements listenerinterface1{

} //Several listener interfaces can be listed, separated by commas.

Step 3: Register the listener object with the appropriate event source.

event_source_object.addevent_listenername(event_listener_object);

//Normally, you use the keyword this for event_listener_object.

Step 4: Define all the methods of the implemented listener interfaces.


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 java.awt.event package. It has five
methods.

Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface are given below:

public abstract void mouseClicked(MouseEvent e);


public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);
Four steps:

Step 1: Include the following import statement:


import java.awt.event.*;

Step 2: Include Implements MouseListener :

public class w2 extends Applet implements MouseListener { }

Step 3: Register addMouseListener method in the applet.


this.addMouseListener (this);

Step 4: Define the five MouseListener methods:

public void mouseClicked(MouseEvent event){


}

public void mouseEntered(MouseEvent event){


}
public void mouseexited(MouseEvent event){
}

public void mousePressed(MouseEvent event){


}

public void mouseReleased(MouseEvent event){


}
Example

The following program changes the applet background color, whenever the
mouse event occurs.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MouseEvent1 extends Applet implements MouseListener{
public void init() {
this.addMouseListener(this);
}public void mouseClicked(MouseEvent e){
setBackground(Color.blue);
}
public void mouseEntered(MouseEvent e){
setBackground(Color.cyan);}
public void mouseExited(MouseEvent e){
setBackground(Color.green);
}
public void mousePressed(MouseEvent e){
setBackground(Color.magenta);
}
public void mouseReleased(MouseEvent e){
setBackground(Color.yellow);
}

Java MouseMotionListener Interface


The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It
has two methods.

Methods of MouseMotionListener interface


The signature of 2 methods found in MouseMotionListener interface are given below:

public abstract void mouseDragged(MouseEvent e);


public abstract void mouseMoved(MouseEvent e);

Java KeyListener Interface


The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package. It has three methods.

public abstract void keyPressed(KeyEvent e);


public abstract void keyReleased(KeyEvent e);
public abstract void keyTyped(KeyEvent e);

import java.awt.*;
import java.awt.event.*;
class keydemo extends Frame implements KeyListener
{
keydemo()
{
addKeyListener(this);
setTitle("Keyeventdemo");
setLayout(null);
setVisible(true);
setSize(400,400);
}
public void keyReleased(KeyEvent ke)
{

setBackground(Color.orange);
}
public void keyPressed(KeyEvent ke)
{
setBackground(Color.cyan);
}
public void keyTyped(KeyEvent ke)
{
setBackground(Color.magenta);
}
public static void main(String[] args)
{
new keydemo();
}
}
Java AWT Dialog
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.

import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Java ActionListener Interface
The Java ActionListener is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in java.awt.event package. It has only
one method: actionPerformed().

actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.

public abstract void actionPerformed(ActionEvent e);

How to write ActionListener


The common approach is to implement the ActionListener. If you implement the ActionListener
class, you need to follow 3 steps:

1) Implement the ActionListener interface in the class:

public class ActionListenerExample Implements ActionListener


2) Register the component with the Listener:

component.addActionListener(instanceOfListenerclass);

3) Override the actionPerformed() method:

Java WindowListener Interface


The Java WindowListener is notified whenever you change the state of window. It is notified against WindowEvent.
The WindowListener interface is found in java.awt.event package. It has three methods.

Methods of WindowListener interface


The signature of 7 methods found in WindowListener interface are given below

public abstract void windowActivated(WindowEvent e);


public abstract void windowClosed(WindowEvent e);
public abstract void windowClosing(WindowEvent e);
public abstract void windowDeactivated(WindowEvent e);
public abstract void windowDeiconified(WindowEvent e);
public abstract void windowIconified(WindowEvent e);
public abstract void windowOpened(WindowEvent e);
EXAMPLE PROGRAM
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();
}
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");
}
}

Java Adapter Classes


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

The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages. The Adapter
classes with their corresponding listener interfaces are given below.

java.awt.event Adapter classes


Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

Java WindowAdapter Example


import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
}
Panel is the simplest container class. A panel provides space in which an
application can attach any other component, including other panels.

The default layout manager for a panel is the FlowLayout layout manager.

Constructor:

Panel ()
Creates a new panel using the default layout manager.
Panel(LayoutManager)
Creates a new panel with the specified layout manager.

You might also like