JAVA Unit 4 Event
JAVA Unit 4 Event
AWT represents a class library to develop applications using GUI. The java.awt
package consists of classes and interfaces to develop GUIs.
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.
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:
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.
3
Unit 4 Event Handling
The package java.awt.event defines many types of events that are generated by various user
interface elements
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.
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
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.
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.
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:
META_DOWN_MASK SHIFT_DOWN_MASK
6
Unit 4 Event Handling
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( )
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)
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:
}
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:
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);
}
});
}
}
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) { }
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
}
}
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");
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
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);
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);
}
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.*;
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.*;
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:
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 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.
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
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
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.*;
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.