0% found this document useful (0 votes)
14 views

JAVA Unit 4 Event

The document discusses AWT components, containers, events and event handling in Java. It describes common AWT components like buttons, text fields and containers. It explains the delegation event model and how events are generated from sources and handled by listeners. It provides examples of different event classes and their corresponding listener interfaces.

Uploaded by

Mayank Saini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

JAVA Unit 4 Event

The document discusses AWT components, containers, events and event handling in Java. It describes common AWT components like buttons, text fields and containers. It explains the delegation event model and how events are generated from sources and handled by listeners. It provides examples of different event classes and their corresponding listener interfaces.

Uploaded by

Mayank Saini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Unit 4 Event Handling

AWT (Abstract Window Toolkit):

AWT represents a class library to develop applications using GUI. The java.awt
package consists of classes and interfaces to develop GUIs.

Component: A component represents an object which is displayed pictorially on the screen


and interacts with the user.

Ex. Button, TextField, TextArea

Container: A Container is a subclass of Component; it has methods that allow other


components to be nested in it. A container is responsible for laying out (that is positioning)
any component that it contains. It does this with various layout managers.

Panel: Panel class is a subclass of Container and is a super class of Applet. When screen
output is redirected to an applet, it is drawn on the surface of the Panel object. In, essence
panel is a window that does not contain a title bar, menu bar or border.

1
Unit 4 Event Handling
Window: A window represents a rectangular area on the screen without any borders or title
bar. The Window class create a top-level window.

Frame: It is a subclass of Window and it has title bar, menu bar, border and resizing
windows.

Delegation Event Model:

The modern approach (from version 1.1 onwards) to handle events is based on the
delegation event model. 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 an event is 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.
A user interface element is able to ―delegate‖ the processing of an event to a separate
piece of code. 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: 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 GUI. 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.

Event Sources: A source is an object that generates an event. Generally sources are
components. 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. For
example, the method that registers a keyboard event listener is called addKeyListener( ).

2
Unit 4 Event Handling
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 )

Event Listeners: A listener is an object that is notified when an event occurs. It has two
major requirements.
1. It must have been registered with one or more sources to receive
notifications about specific types of events.
2. It must implement methods to receive and process these notifications.

The methods that receive and process events are defined in a set of interfaces found in
java.awt.event package.

Sources of Events:

Event Source Description


Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked;
Generates action events when a menu item is selected; generates item
Menu item events when a checkable menu item is selected or deselected.
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Generates window events when a window is activated, closed,
Window
deactivated, deiconified, iconified, opened, or quit.

Event Classes and Listener Interfaces:

The java.awt.event package provides many event classes and Listener interfaces for
event handling. At the root of the Java event class hierarchy is EventObject, which is in
java.util. It is the super class for all events. It‘s one constructor is shown here:

EventObject(Object src) - Here, src is the object that generates this event.

EventObject contains two methods:


Object getSource( ) - Object on which event initially occurred.
String toString( ) - toString( ) returns the string equivalent of the event.

The class AWTEvent, defined within the java.awt package, is a subclass of


EventObject. It is the superclass (either directly or indirectly) of all AWT-based events used
by the delegation event model. Its getID( ) method can be used to determine the type of the
event. The signature of this method is shown here:
int getID( )
.

3
Unit 4 Event Handling

The package java.awt.event defines many types of events that are generated by various user
interface elements

Event Class Description Listener Interface


Generated when a button is pressed, a list
ActionEvent item is double-clicked, or a menu item is ActionListener
selected.
AdjustmentEvent Generated when a scroll bar is manipulated. AdjustmentListener
Generated when a component is hidden,
ComponentEvent ComponentListener
moved, resized, or becomes visible.
Generated when a component is added to or
ContainerEvent ContainerListener
removed from a container.
Generated when a component gains or
FocusEvent FocusListener
losses keyboard focus.
Abstract super class for all component input
InputEvent
event classes.
Generated when a check box or list item is
ItemEvent ItemListener
clicked
Generated when input is received from the
KeyEvent KeyListener
keyboard.
Generated when the mouse is dragged,
moved, clicked, pressed, or released; MouseListener and
MouseEvent
also generated when the mouse enters or MouseMotionListener
exits a component.
Generated when the value of a text area or
TextEvent TextListener
text field is changed.
Generated when a window is activated,
WindowEvent closed, deactivated, deiconified, iconified, WindowListener
opened, or quit.

Useful Methods of Component class:

Method Description
public void add(Component c) inserts a component.
sets the size (width and height) of the
public void setSize(int width,int height)
component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
changes the visibility of the component, by
public void setVisible(boolean status)
default false.

4
Unit 4 Event Handling
The ActionEvent Class:
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or
a menu item is selected.
The ActionEvent class defines four integer constants that can be used to identify any
modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK (Ex.
Escape), and SHIFT_MASK.

ActionEvent has these three constructors:


o ActionEvent(Object src, int type, String cmd)
o ActionEvent(Object src, int type, String cmd, int modifiers)
o ActionEvent(Object src, int type, String cmd, long when, int modifiers)

You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand( ) method, shown here:
String getActionCommand( ) -Returns the command string associated
with this action

The AdjustmentEvent Class:

An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.

The user clicked inside the scroll bar to decrease its


BLOCK_DECREMENT
value.
The user clicked inside the scroll bar to increase its
BLOCK_INCREMENT
value.
TRACK The slider was dragged.
The button at the end of the scroll bar was clicked to
UNIT_DECREMENT
decrease its value.
The button at the end of the scroll bar was clicked to
UNIT_INCREMENT
increase its value.

The ComponentEvent Class:

A ComponentEvent is generated when the size, position, or visibility of a component


is changed. There are four types of component events. The ComponentEvent class defines
integer constants that can be used to identify them:
COMPONENT_HIDDEN The component was hidden.
COMPONENT_MOVED The component was moved.
COMPONENT_RESIZED The component was resized.
COMPONENT_SHOWN The component became visible.

ComponentEvent is the superclass either directly or indirectly of ContainerEvent,


FocusEvent, KeyEvent, MouseEvent, and WindowEvent, among others.

The getComponent( ) method returns the component that generated the event. It is
shown here:
5
Unit 4 Event Handling
Component getComponent( )
The ContainerEvent Class:
A ContainerEvent is generated when a component is added to or removed from a
container. There are two types of container events. The ContainerEvent class defines
constants that can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED.

The FocusEvent Class:


A FocusEvent is generated when a component gains or loses input focus. These
events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.

The InputEvent Class:


The abstract class InputEvent is a subclass of ComponentEvent and is the super
class for component input events. Its subclasses are KeyEvent and MouseEvent.
InputEvent defines several integer constants that represent any modifiers, such as the
control key being pressed, that might be associated with the event. Originally, the InputEvent
class defined the following eight values to represent the modifiers:

ALT_MASK ALT_GRAPH_MASK BUTTON2_MASK BUTTON3_MASK


BUTTON1_MASK CTRL_MASK META_MASK SHIFT_MASK

However, because of possible conflicts between the modifiers used by keyboard events and
mouse events, and other issues, the following extended modifier values were added:

ALT_DOWN_MASK ALT_GRAPH_DOWN_MASK BUTTON1_DOWN_MASK

BUTTON2_DOWN_MASK BUTTON3_DOWN_MASK CTRL_DOWN_MASK

META_DOWN_MASK SHIFT_DOWN_MASK

The KeyEvent Class


A KeyEvent is generated when keyboard input occurs. There are three types of
key events, which are identified by these integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED.
The first two events are generated when any key is pressed or released. The last event
occurs only when a character is generated. Remember, not all key presses result in characters.
For example, pressing shift does not generate a character.
There are many other integer constants that are defined by KeyEvent. For example,
VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers
and letters.

6
Unit 4 Event Handling

The MouseEvent Class:


There are eight types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse
MOUSE_DRAGGED The user dragged the mouse
MOUSE_ENTERED The mouse entered a component
MOUSE_EXITED The mouse exited from a
component.
MOUSE_MOVED The mouse moved
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved.

Two commonly used methods in this class are getX( ) and getY( ). These return the X
and Y coordinates of the mouse within the component when the event occurred. Their forms
are shown here:
int getX( )
int getY( )

The TextEvent Class:


Instances of this class describe text events. These are generated by text fields and text
areas when characters are entered by a user or program. TextEvent defines the integer
constant TEXT_VALUE_CHANGED.

The WindowEvent Class:


The WindowEvent class defines integer constants that can be used to identify
different types of events:

WINDOW_ACTIVATED The window was activated.


WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window was iconified.
WINDOW_ICONIFIED The window gained input focus.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.

7
Unit 4 Event Handling
EventListener Interfaces:

An event listener registers with an event source to receive notifications about the
events of a particular type. Various event listener interfaces defined in the java.awt.event
package are given below:

Interface Description
Defines the actionPerformed() method to receive and process
ActionListener action events.
void actionPerformed(ActionEvent ae)
Defines five methods to receive mouse events, such as when a
mouse is clicked, pressed, released, enters, or exits a component
void mouseClicked(MouseEvent me)
MouseListener void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
Defines two methods to receive events, such as when a mouse is
dragged or moved.
MouseMotionListener
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
Defines the adjustmentValueChanged() method to receive and
AdjustmentListner process the adjustment events.
void adjustmentValueChanged(AdjustmentEvent ae)
Defines the textValueChanged() method to receive and process an
TextListener event when the text value changes.
void textValueChanged(TextEvent te)
Defines seven window methods to receive events.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
WindowListener
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
Defines the itemStateChanged() method when an item has been
ItemListener
void itemStateChanged(ItemEvent ie)
This interface defines two methods: windowGainedFocus( ) and
windowLostFocus( ). These are called when a window gains or
WindowFocusListener loses input focus. Their general forms are shown here:
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
This interface defines four methods that are invoked when a
component is resized, moved, shown, or hidden. Their general
forms are shown here:
ComponentListener void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

8
Unit 4 Event Handling
This interface contains two methods. When a component is added
to a container, componentAdded( ) is invoked. When a
component is removed from a container, componentRemoved( )
ContainerListener is invoked.
Their general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
This interface defines two methods. When a component obtains
keyboard focus, focusGained( ) is invoked. When a component
loses keyboard focus, focusLost( ) is called. Their general forms
FocusListener
are shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
This interface defines three methods.
void keyPressed(KeyEvent ke)
KeyListener
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

Steps to perform Event Handling

Following steps are required to perform event handling:


1. Register the component with the Listener
2. Implement the concerned interface

Registration Methods:

For registering the component with the Listener, many classes provide the registration
methods. For example:

 Button
o public void addActionListener(ActionListener a){}
 MenuItem
o public void addActionListener(ActionListener a){}
 TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
 TextArea
o public void addTextListener(TextListener a){}
 Checkbox
o public void addItemListener(ItemListener a){}
 Choice
o public void addItemListener(ItemListener a){}
 List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
 Mouse
o public void addMouseListener(MouseListener a){}

9
Unit 4 Event Handling
Handling Mouse Events Example Program:

// Demonstrate the mouse event handlers.


import java.awt.*;
import java.awt.event.*;
class MouseDemo extends Frame implements MouseListener
{
String msg="";
MouseDemo()
{
addMouseListener(this);

}
public void mouseClicked(MouseEvent me)
{
msg="mouse clicked"; repaint();
}
public void mouseEntered(MouseEvent me)
{ msg="mouse entered";repaint();
}
public void mouseExited(MouseEvent me){
msg="mouse exited";repaint();
}
public void mousePressed(MouseEvent me){
msg="mouse pressed";repaint();
}
public void mouseReleased(MouseEvent me){
msg="mouse released";repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,200,200);
}
}
class MouseEventsExample
{
public static void main(String arg[])
{
MouseDemo d=new MouseDemo();
d.setSize(400,400);
d.setVisible(true);
d.setTitle("Mouse Events Demo Program");

d.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}
10
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
Output:

Handling Key Board Events:

import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements KeyListener
{
String keystate="Hello PVPSIT";
String msg="";
MyFrame()
{
addKeyListener(this);
addWindowListener(new MyWindow() );
}
public void keyPressed(KeyEvent ke)
{
keystate="Key Pressed";
msg+=ke.getKeyText( ke.getKeyCode());
repaint();
}
public void keyTyped(KeyEvent ke)
{
keystate="Key Typed"; repaint();
msg=msg+ke.getKeyChar();
}
public void keyReleased(KeyEvent ke)
{
keystate="Key Released"; repaint();
}
public void paint(Graphics g)
{
g.drawString(keystate,100,50);
g.drawString(msg,100,100);
}
11
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
}
class KeyEventsExample
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setTitle("Key Events Example");
f.setSize(500,300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

}
}

Window Events Example Program:


import java.awt.*;
import java.awt.event.*;
class WindowEx1 extends Frame implements WindowListener
{
String msg;
WindowEx1(){
addWindowListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg,150,200);
}
public void windowActivated(WindowEvent arg0) {
msg="activated";
repaint();
}
public void windowClosed(WindowEvent arg0) {
msg="closed"; repaint();
}
public void windowClosing(WindowEvent arg0) {
System.out.println("closing");
System.exit(0);
}
public void windowDeactivated(WindowEvent arg0) {
msg="deactivated" ;
}
public void windowDeiconified(WindowEvent arg0) {
msg="deiconified" ; repaint();
}
public void windowIconified(WindowEvent arg0) {
msg="iconified" ; repaint();
12
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
}
public void windowOpened(WindowEvent arg0) {
msg="opened" ; repaint();
}
}
class WindowExample
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
w.setSize(400,400);
w.setLayout(null);
w.setVisible(true);
}
}

Adapter Classes:

Java provides a special feature, called an adapter class, that can simplify the creation
of event handlers in certain situations. An adapter class provides an empty implementation of
all methods in an event listener interface. Adapter classes are useful when you want to
receive and process only some of the events that are handled by a particular event listener
interface.
For example,
MouseListener MouseAdapter
void mouseClicked(MouseEvent me) void mouseClicked(MouseEvent me){ }
void mouseEntered(MouseEvent me) void mouseEntered(MouseEvent me) { }
void mouseExited(MouseEvent me) void mouseExited(MouseEvent me) { }
void mousePressed(MouseEvent me) void mousePressed(MouseEvent me) { }
void mouseReleased(MouseEvent me) void mouseReleased(MouseEvent me) { }

Table: Commonly used Listener Interfaces implemented by Adapter Classes


Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

Example Program

import java.awt.*;
import java.awt.event.*;
class WindowEx1 extends Frame
{
String msg;

13
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
WindowEx1(){
addWindowListener(new WA());
}
}
class WA extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
class WindowAdapterEx
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
w.setSize(400,400);
w.setLayout(null);
w.setVisible(true);
}
}

Inner Classes:

Inner class is a class defined within another class, or even within an expression.

Example:
import java.awt.*;
import java.awt.event.*;
class WindowEx1 extends Frame
{
String msg;
WindowEx1(){
addWindowListener(new WA());
}
class WA extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
}
class WindowAdapterInner
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
w.setSize(400,400);
w.setLayout(null);
w.setVisible(true);

14
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
}
}

Anonymous Inner Classes:

An anonymous inner class is one that is not assigned a name.

Example:

import java.awt.*;
import java.awt.event.*;
class WindowEx1 extends Frame
{
String msg;
WindowEx1(){
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}
class WindowAdapterAnonymous
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
w.setSize(400,400);
w.setLayout(null);
w.setVisible(true);
}
}

Control Fundamentals:
The AWT supports the following types of controls:
 Labels
 Push buttons
 Check boxes
 Choice lists
 Lists
 Scroll bars
 Text Editing
These controls are subclasses of Component

Adding and Removing Controls: To include a control in a window, you must add it to the
window. To do this, you must first create an instance of the desired control and then add it to
a window by calling add(), which is defined by Container.
The General form is:
15
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
Component add(Component compObj)
Here, compObj is an instance of the control that you want to add. A reference to compObj is
returned.
Sometimes you will want to remove a control from a window when the control is no
longer needed. To do this, call remove( ). This method is also defined by Container. Here is
one of its forms:
void remove(Component obj)
Here, obj is a reference to the control you want to remove. You can remove all controls by
calling removeAll( ).

The HeadlessException:
Most of the AWT controls have constructors that can throw a HeadlessException
when an attempt is made to instantiate a GUI component in a non-interactive environment
(such as one in which no display, mouse, or keyboard is present).

Labels:
A label is an object of type Label, and it contains a string, which it displays. Labels
are passive controls that do not support any interaction with the user. Label defines the
following constructors:
Label( ) throws HeadlessException
Label(String str) throws HeadlessException
Label(String str, int how) throws HeadlessException
The first version creates a blank label. The second version creates a label that contains
the string specified by str. This string is left-justified. The third version creates a label that
contains the string specified by str using the alignment specified by how. The value of how
must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.

Using Buttons:
A push button is a component that contains a label and that generates an event when
it is pressed. Push buttons are objects of type Button. Button defines these two constructors:
Button( ) throws HeadlessException
Button(String str) throws HeadlessException
The first version creates an empty button. The second creates a button that contains
str as a label.
After a button has been created, you can set its label by calling setLabel( ). You can
retrieve its label by calling getLabel( ). These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button

Example:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
16
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
{
Button b1,b2,b3;
MyFrame()
{
b1=new Button("Red");
b2=new Button("Green");
b3=new Button("Blue");
add(b1); add(b2); add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand()=="Red")
setBackground(new Color(255,0,0));
if(ae.getActionCommand()=="Green")
setBackground(new Color(0,255,0));
if(ae.getActionCommand()=="Blue")
setBackground(new Color(0,0,255));
}
}
class ButtonDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Or

import java.awt.*;
import java.awt.event.*;

17
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
class MyFrame extends Frame
{
Button b1,b2,b3;
MyFrame()
{
b1=new Button("Red");
b2=new Button("Green");
b3=new Button("Blue");
add(b1); add(b2); add(b3);

}
class ButtonDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

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. Check boxes can be used individually or
as part of a group. Check boxes are objects of the Checkbox class.
Checkbox supports these constructors:
Checkbox( ) throws HeadlessException
Checkbox(String str) throws HeadlessException
Checkbox(String str, boolean on) throws HeadlessException
Checkbox(String str, boolean on, CheckboxGroup cbGroup) throws HeadlessException
Checkbox(String str, CheckboxGroup cbGroup, boolean on) throws HeadlessException

18
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
The first form creates a check box whose label is initially blank. The state of the
check box is unchecked. The second form creates a check box whose label is specified by str.
The state of the check box is unchecked. The third form allows you to set the initial state of
the check box. If on is true, the check box is initially checked; otherwise, it is cleared. The
fourth and fifth forms create a check box whose label is specified by str and whose group is
specified by cbGroup. If this check box is not part of a group, then cbGroup must be null.
The value of on determines the initial state of the check box.
Methods:
boolean getState( ) - To retrieve the current state of a check box
void setState(boolean on) - to set the state of a check box
String getLabel( ) – returns the label associated with check box
void setLabel(String str) – to set the label
Example:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ItemListener
{
String msg="";
Checkbox m,f,t;
MyFrame()
{
m=new Checkbox();
m.setLabel("Male");
f=new Checkbox("Female",true);
t=new Checkbox("Transzender");

add(m); add(f); add(t);


m.addItemListener(this);
f.addItemListener(this);
t.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current State";
g.drawString(msg,150,150);

msg="Male (True/False)"+m.getState();
g.drawString(msg,150,200);

19
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
msg="Female (True/False)"+f.getState();
g.drawString(msg,150,250);

msg="Transzender (True/False)"+t.getState();
g.drawString(msg,150,300);
}
}
class Demo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Or

import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
Checkbox m,f,t;
MyFrame()
{
m=new Checkbox();
m.setLabel("Male");
f=new Checkbox("Female",true);
t=new Checkbox("Transzender");
add(m); add(f); add(t);
}
}
class Demo
{
public static void main(String arg[])

20
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

CheckboxGroup:
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 check boxes are often
called radio buttons —only one button can be selected at any one time.
To create a set of mutually exclusive check boxes, you must first define the group to
which they will belong and then specify that group when you construct the check boxes.
Check box groups are objects of type CheckboxGroup.
Only the default constructor is defined, which creates an empty group.
Methods:
Checkbox getSelectedCheckbox( ) - which check box in a group is currently selected
void setSelectedCheckbox(Checkbox which) - which is the check box that you want to
be selected. The previously selected check box will be turned off

Example:

import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ItemListener
{
String msg="";
Checkbox m,f,t;
CheckboxGroup cbg;
MyFrame()
{
cbg=new CheckboxGroup();
m=new Checkbox("Male",false,cbg);
f=new Checkbox("Female",false,cbg);
t=new Checkbox("Transzender",false,cbg);
cbg.setSelectedCheckbox(f);

21
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling

add(m); add(f); add(t);


m.addItemListener(this);
f.addItemListener(this);
t.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current State : " +cbg.getSelectedCheckbox();
g.drawString(msg,150,150);
}
}
class Demo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Or
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
Checkbox m,f,t;
CheckboxGroup cbg;
MyFrame()
{

22
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
cbg=new CheckboxGroup();
m=new Checkbox("Male",false,cbg);
f=new Checkbox("Female",false,cbg);
t=new Checkbox("Transzender",false,cbg);
cbg.setSelectedCheckbox(f);

add(m); add(f); add(t);


}
}
class Demo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Choice Controls:
The Choice class is used to create a pop-up list of items from which the user may
choose. Choice defines only the default constructor, which creates an empty list. To add a
selection to the list, call add( ). It has this general form:

void add(String name) - name is the name of the item being added.
Items are added to the list in the order in which calls to add( ) occur.
Methods:
String getSelectedItem( ) – returns the item which is currently selected
int getSelectedIndex( ) - returns the index of the item. The first item is at index 0. By
default, the first item added to the list is selected.
int getItemCount( ) – returns number of items in the list
void select(int index) - to set the currently selected item with index
void select(String name) - to set the currently selected item with a string
String getItem(int index) – returns the name associated with the index
Example:

23
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
mport java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ItemListener
{
Choice c;
String msg="";
MyFrame()
{
c=new Choice();
c.add("PVPSIT");
c.add("VRSEC");
c.add("BEC");
c.add("RVR&JC");
add(c);
c.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current Selection : "+c.getSelectedItem();
g.drawString(msg, 150,150);

msg="Selected Index : "+c.getSelectedIndex();


g.drawString(msg, 150,200);

msg="Total No of Items : "+c.getItemCount();


g.drawString(msg, 150,250);
}

}
class ChoiceDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){

24
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Or
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
Choice c;

MyFrame()
{
c=new Choice();
c.add("PVPSIT");
c.add("VRSEC");
c.add("BEC");
c.add("RVR&JC");
add(c);
}

}
class ChoiceDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

25
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
List:
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.
List provides these constructors:
List( ) throws HeadlessException
List(int numRows) throws HeadlessException
List(int numRows, boolean multipleSelect) throws HeadlessException
The first version creates a List control that allows only one item to be selected at any
one time. In the second form, the value of numRows specifies the number of entries in the list
that will always be visible (others can be scrolled into view as needed). In the third form, if
multipleSelect is true, then the user may select two or more items at a time. If it is false, then
only one item may be selected.
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)
Here, name is the name of the item added to the list. The first form adds items to the
end of the list. The second form adds the item at the index specified by index. Indexing
begins at zero. You can specify –1 to add the item to the end of the list.

Example:
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;

class MyFrame extends Frame implements ActionListener


{
List l;
String msg="";
MyFrame()
{
l=new List(2,true);
l.add("PVPSIT");
l.add("VRSEC");
l.add("BEC");
l.add("RVR&JC");
add(l);

l.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();

26
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
}
public void paint(Graphics g)
{
for(int i:l.getSelectedIndexes())
msg+=i;
g.drawString(msg,150,150);
msg="";
for(String i:l.getSelectedItems())
msg+=i;
g.drawString(msg,150,200);

}
}
class ListDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Or
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;

class MyFrame extends Frame


{
List l;
String msg="";
MyFrame()
{
l=new List(2,true);

27
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
l.add("PVPSIT");
l.add("VRSEC");
l.add("BEC");
l.add("RVR&JC");
add(l);

}
}
class ListDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

TextField:
The TextField class implements a single-line text-entry area. Text fields allow the
user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse
selections.
TextField is a subclass of TextComponent. TextField defines the following
constructors:
TextField( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException
The first version creates a default text field. The second form creates a text field that
is numChars characters wide. The third form initializes the text field with the string contained
in str. The fourth form initializes a text field and sets its width.
Methods:
 String getText( ) - To obtain the string currently contained in the text field
28
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
 void setText(String str) - To set the text, here, str is the new string.
 String getSelectedText( ) - returns currently selected text
 void select(int startIndex, int endIndex) - selects the characters beginning at startIndex
and ending at endIndex –1.
 boolean isEditable( ) – returns boolean value (true/false)
 void setEditable(boolean canEdit) - if canEdit is true, the text may be changed. If it is
false, the text cannot be altered.
 void setEchoChar(char ch) – specified echo character will be displayed in TextField
 boolean echoCharIsSet( ) –returns true or false
 char getEchoChar( ) – returns the echo character

Example:

import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements TextListener
{
TextField t ;
String msg="";
MyFrame()
{
Label l=new Label("Enter Name");
t=new TextField(35);
add(l);
add(t);

t.addTextListener(this);
}
public void textValueChanged(TextEvent te)
{
repaint();
}
public void paint(Graphics g)
{
msg="Text in the Field : "+t.getText();
g.drawString(msg,150,150);
msg="Text in the Field : "+t.getSelectedText();
g.drawString(msg,150,200);

msg="is editable:"+t.isEditable();
g.drawString( msg ,150,250);

}
}
29
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
class TextFieldDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}
Or

import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
TextField t ;
String msg="";
MyFrame()
{
Label l=new Label("Enter Name");
t=new TextField(35);
add(l);
add(t);
}
}
class TextFieldDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)

30
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
{
System.exit(0);
}
});
}
}

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
Here, numLines specifies the height, in lines, of the text area, and numChars specifies
its width, in characters. Initial text can be specified by str. In the fifth form, you can specify
the scroll bars that you want the control to have. sBars must be one of these values:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
TextArea is a subclass of TextComponent. Therefore, it supports the getText( ),
setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described
in the preceding section.
TextArea adds the following methods:
void append(String str) - appends the string specified by str to the end of the current
void insert(String str, int index) - inserts the string passed in str at the specified index
void replaceRange(String str, int startIndex, int endIndex) - replaces the characters
from startIndex to endIndex–1, with the replacement text passed in str

Example:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
TextArea ta;
MyFrame()
{
ta=new TextArea("PVP Siddhartha Inst. of Technology");

add(ta);
}
31
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
}
class TextDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Scroll Bars:
Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.
Scroll bars are encapsulated by the Scrollbar class. Scrollbar defines the following
constructors:
Scrollbar( ) throws HeadlessException
Scrollbar(int style) throws HeadlessException
Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws
HeadlessException

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. The
number of units represented by the height of the thumb is passed in thumbSize. The minimum
and maximum values for the scroll bar are specified by min and max.

Methods:

void setValues(int initialValue, If we construct a scroll bar by using one of the


int thumbSize, int min, int max) first two constructors, then you need to set its
parameters by using setValues()
int getValue( ) To get the current value
void setValue(int newValue) TO set the current value
int getMinimum( ) To get the minimum value
int getMaximum( ) To get the maximum value

32
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
Example:

import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements AdjustmentListener
{
Scrollbar r,g,b;
String msg="";
MyFrame()
{
r=new Scrollbar(0,20,10,1,255);
g=new Scrollbar(1,20,10,1,255);
b=new Scrollbar(0,20,10,1,255);
add(r,"South");
add(g,"East");
add(b,"North");
r.addAdjustmentListener(this);
g.addAdjustmentListener(this);
b.addAdjustmentListener(this);

}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
setBackground(new Color(r.getValue(),g.getValue(),b.getValue()));
}

}
class ScrollbarDemo2
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Scrollbar Programs...");
f.setVisible(true);
f.setLayout(new BorderLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Or

import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
33
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
{
Scrollbar r,g,b;
String msg="";
MyFrame()
{
r=new Scrollbar(0,20,10,1,255);
g=new Scrollbar(1,20,10,1,255);
b=new Scrollbar(0,20,10,1,255);
add(r );
add(g);
add(b);

}
class ScrollbarDemo2
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Scrollbar Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Layout Manager
A layout manager is a class that is useful to arrange components in a particular
manner in container or a frame.
Java soft people have created a LayoutManager interface in java.awt package which is
implemented in various classes which provide various types of layouts to arrange the
components. The following classes represents the layout managers in Java:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
6. BoxLayout

To set a particular layout, we should first create an object to the layout class and pass
the object to setLayout() method. For example, to set FlowLayout to the container:
34
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
FlowLayout obj=new FlowLayout();
c. setLayout(obj); // assume c is container

FlowLayout:
FlowLayout is useful to arrange the components in a line one after the other. When a
line is filled with components, they are automatically placed in a next line. This is the default
layout in applets.
Constructors:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centres 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
The third constructor allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.

Example:
import java.awt.*;
import java.awt.event.*;

class MyFrame extends Frame


{
List l;
String msg="";
MyFrame()
{
l=new List(2,true);
l.add("PVPSIT");
l.add("VRSEC");
l.add("BEC");
l.add("RVR&JC");
add(l);

}
}
class ListDemo
{
public static void main(String arg[])
{

35
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

BorderLayout:
BorderLayout is useful to arrange the components in the four borders of the frame as
well as in the centre. The borders are identified with the names of the directions. The top
border is specified as ‗North‘, the right side border as ‗East‘, the bottom one as ‗South‘ and
the left one as ‗West‘. The centre is represented as ‗Centre‘.
Constructors:
 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.

Example:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
Button b1,b2,b3,b4,b5;

36
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
MyFrame()
{
b1=new Button("East");
b2=new Button("West");
b3=new Button("South");
b4=new Button("North");
b5=new Button("Center");
add(b1,"East");
add(b2,"West");
add(b3,"South");
add(b4,"North");
add(b5,"Center");
}
}
class BorderDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

GridLayout:
GridLayout is useful to divide the container into a 2D grid form that contains several
rows and columns. The container is divided into equal-sized rectangle; and one component is
placed in each rectangle.

Constructors:
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.
37
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
Either numRows or numColumns can be zero. Specifying numRows as zero allows for
unlimitedlength columns. Specifying numColumns as zero allows for unlimited-length rows.

Example:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
Button b1,b2,b3,b4;
MyFrame()
{
setLayout(new GridLayout(2,2,20,20));
b1=new Button("PVP");
b2=new Button("VRSEC");
b3=new Button("BEC");
b4=new Button("RVR&JC");
add(b1 );
add(b2);
add(b3);
add(b4);
}
}
class GridDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

CardLayout:
A CardLayout object is a layout manager which treats each component as a card.
Only one card is displayed at a time, and the container acts as a stack of cards. The first

38
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
component added to a CardLayout object is visible component when the container is first
displayed.

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.
Use of a card layout requires a bit more work than the other layouts. The cards are
typically held in an object of type Panel. This panel must have CardLayout selected as its
layout manager. Finally, you add this pane to the window.
Once these steps are complete, you must provide some way for the user to select
between cards. One common approach is to include one push button for each card in the
deck. When card panels are added to a panel, they are usually given a name. Thus, most of
the time, you will use this form of add( ) when adding cards to a panel:
void add(Component panelObj, Object name)
or
void add(Object name, Component panelObj)
Here, name is a string that specifies the name of the card whose panel is specified by
panelObj. After you have created a deck, your program activates a card by calling one of the
following methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)

Example:

// Demonstrate CardLayout.
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener
{
Checkbox winXP, win7, solaris, mac;
Panel osCards;
CardLayout cardLO;
Button Win, Other;

MyFrame()
{
Win = new Button("Windows");
Other = new Button("Other");
add(Win);
add(Other);

39
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
cardLO = new CardLayout();
osCards = new Panel();
osCards.setLayout(cardLO); // set panel layout to card layout

winXP = new Checkbox("Windows 7");


win7 = new Checkbox("Windows 10");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

// add Windows check boxes to a panel


Panel winPan = new Panel();
winPan.add(winXP);
winPan.add(win7);

// add other OS check boxes to a panel


Panel otherPan = new Panel();
otherPan.add(solaris);
otherPan.add(mac);

// add panels to card deck panel


osCards.add(winPan, "Windows");
osCards.add(otherPan, "Other");
// add cards to main applet panel
add(osCards);
// register to receive action events
Win.addActionListener(this);
Other.addActionListener(this);
// register mouse events
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == Win) {
cardLO.show(osCards, "Windows");
}
else {
cardLO.show(osCards, "Other");
}
}
}

class CardLayoutDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();

40
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
f.setSize(200,200);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

GridBagLayout:
A GridBagLayout class represents grid bag layout manager where the components are
arranged in rows and columns. In this layout the component can span more than one row or
column and the size of the component can be adjusted to fit in the display area.
When positioning the components by using grid bag layout, it is necessary to apply
some constraints or conditions on the components regarding their position, size and place in
or around the components etc. Such constraints are specified using GridBagConstrinats class.
In order to create GridBagLayout, we first instantiate the GridBagLayout class
by using its only no-argument constructor
GridBagLayout layout=new GridBagLayout();
setLayout(layout);
and defining it as the current layout manager.
To apply constraints on the components, we should first create an object to
GridBagConstrinats class, as
GridBagConstrinats gbc =new GridBagConstrinats();
This will create constraints for the components with default value. The other way to
specify the constraints is by directly passing their values while creating the
GridBagConstrinats as
GridBagConstrinats gbc= new GridBagConstrinats(
int gridx, int gridy, int gridwidth, int gridheight, double weightx,
double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady );

To set the constraints use setConstraints() method in GridBagConstrinats class and its
prototype
void setConstraints(Component comp, GridBagConstraints cons);

41
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
Constraint fields Defined by GridBagConstraints:

Field Purpose
Specifies the location of a component within a cell. The
default is GridBagConstraints.CENTER. Others are
 GridBagConstraints.EAST
 GridBagConstraints.WEST
 GridBagConstraints.SOUTH
int anchor
 GridBagConstraints.NORTH
 GridBagConstraints.NORTHEAST
 GridBagConstraints.NORTHWEST
 GridBagConstraints.SOUTHEAST
 GridBagConstraints.SOUTHWEST
Specifies the X coordinate of the cell to which the
int gridx
component will be added.
Specifies the Y coordinate of the cell to which the
int gridy
component will be added.
Specifies the height of component in terms of cells. The
int gridheight
default is 1.
Specifies the width of component in terms of cells. The
int gridwidth
default is 1.
Specifies a weight value that determines the horizontal
spacing between cells and the edges of the container that
double weightx
holds them. The default value is 0.0. The greater the weight,
the more space that is allocated.
Specifies a weight value that determines the vertical spacing
double weighty between cells and the edges of the container that holds them.
The default value is 0.0.
Specifies extra horizontal space that surrounds a component
within a cell. The default is 0.

int ipadx

Specifies extra vertical space that surrounds a component


int ipady
within a cell. The default is 0.
Specifies how a component is resized if the component is
smaller than its cell. Valid values are
 GridBagConstraints.NONE (the default)
int fill
 GridBagConstraints.HORIZONTAL
 GridBagConstraints.VERTICAL
 GridBagConstraints.BOTH.

42
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
Small amount of space between the container that holds
your components and the window that contains it. Default
insets are all zero.
Ex. Insets i=new Insets(5,10,20,15);
Insets insets

Example:

// Use GridBagLayout.
import java.awt.*;
import java.awt.event.*;

class MyFrame extends Frame


{
Button b1,b2,b3,b4,b5,b6,b7,b8,b9;
MyFrame()
{
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);

b1=new Button("Button 1");


b2=new Button("Button 2");
b3=new Button("Button 3");
b4=new Button("Button 4");
b5=new Button("Button 5");
b6=new Button("Button 6");
b7=new Button("Button 7");
b8=new Button("Button 8");
b9=new Button("Button 9");

gbc.gridx=0;
gbc.gridy=0;
gbag.setConstraints(b1,gbc);
gbc.gridx=1;
gbc.gridy=0;
gbag.setConstraints(b2,gbc);
gbc.gridx=2;
gbc.gridy=0;
gbag.setConstraints(b3,gbc);
gbc.gridx=0;
gbc.gridy=1;
gbag.setConstraints(b4,gbc);
gbc.gridx=1;
gbc.gridy=1;
gbag.setConstraints(b5,gbc);
43
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.
Unit 4 Event Handling
gbc.gridx=2;
gbc.gridy=1;
gbag.setConstraints(b6,gbc);
gbc.gridx=0;
gbc.gridy=2;
gbag.setConstraints(b7,gbc);
gbc.gridx=1;
gbc.gridy=2;
gbag.setConstraints(b8,gbc);
gbc.gridx=2;
gbc.gridy=2;
gbag.setConstraints(b9,gbc);

add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
}
}
class GridBagDemo2
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);
//f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

44
Dr. Suresh Yadlapati, Dept of IT, PVPSIT.

You might also like