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

Java Lec15 Event Handling

Uploaded by

Bhavya Sree
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Lec15 Event Handling

Uploaded by

Bhavya Sree
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 84

EVENT HANDLING

• applets are event-driven programs that use a graphical


user interface to interact with the user
• Events are supported by a number of packages,
including java.util, java.awt, and java.awt.event
THE DELEGATION EVENT MODEL
• The modern approach to handling events is based on
the delegation event model
• defines standard and consistent mechanisms to
generate and process events
• a source generates an event and sends it to one or
more listeners
• the listener simply waits until it receives an event
• Once an event is received, the listener processes the
event and then returns
• In the delegation event model, listeners must register
with a source in order to receive an event notification
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 graphical user
interface
• Some of the activities that cause events to be
generated are
• pressing a button,
• entering a character via the keyboard,
• selecting an item in a list, and clicking the mouse.
• Many other user operations
EVENT SOURCES

• A source is an object that generates an event.


• This occurs when the internal state of that object changes
in some way.
• Sources may generate more than one type of event.
• A source must register listeners in order for the listeners to
receive notifications about a specific type of event.
• Each type of event has its own registration method.
• general form: public void addTypeListener(TypeListener el)
• Type is the name of the event and el is a reference to the event listener
• Example:the method that registers a keyboard event listener is
addKeyListener( )
EVENT LISTENERS

• A listener is an object that is notified when an event


occurs.
• It has two major requirements.
• it must have been registered with one or more sources to receive
notifications
• it must implement methods to receive and process these
notifications.
EVENT CLASSES

• The most widely used events are those defined by the


AWT and those defined by Swing.
• At the root of the Java event class hierarchy is
EventObject, which is in java.util. It is the
superclass for all events.
MAIN EVENT CLASSES IN java.awt.event
THE MOUSE EVENT CLASS
SOURCES OF EVENTS
EVENT LISTENER INTERFACES

• Listeners are created by implementing one or more of


the interfaces defined by the java.awt.event package
• When an event occurs, the event source invokes the
appropriate method defined by the listener and
provides an event object as its argument.
COMMONLY USED LISTENER
INTERFACES
THE ACTIONLISTENER INTERFACE

• This interface defines the actionPerformed( )


method that is invoked when an action event occurs.
Its general form is shown here:
• void actionPerformed(ActionEvent ae)
• The KeyListener Interface
• void keyPressed(KeyEvent ke)
• void keyReleased(KeyEvent ke)
• void keyTyped(KeyEvent ke)
• The MouseListener Interface
• void mouseClicked(MouseEvent me)
• void mouseEntered(MouseEvent me)
• void mouseExited(MouseEvent me)
• void mousePressed(MouseEvent me)
• void mouseReleased(MouseEvent me)
HANDLING MOUSE EVENTS PROGRAM
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements MouseListener,
MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + me.getX() + ", " +
me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
} output
AWT(ABSTRACT WINDOW TOOLKIT

• The AWT contains numerous classes and methods that


allow us to create and manage windows
• AWT classes are mainly used in applets for creating
stand-alone windows that run in a GUI environment
• The AWT classes are contained in the java.awt
package.
AWT CLASSES
AWT CLASSES CONTD.
WINDOW FUNDAMENTALS

• The AWT defines windows according to a class


hierarchy that adds functionality and specificity with
each level.
• The two most common windows are those derived from
• Panel, which is used by applets,
• and those derived from Frame, which creates a standard
application window.
• Component class: is At the top of the AWT hierarchy
• is an abstract class that encapsulates all of the attributes of a
visual component.
• All user interface elements that are displayed on the screen and
that interact with the user are subclasses of Component.
• It defines over a hundred public methods that are responsible for
managing events, such as mouse and keyboard input, positioning
• Container class:is a subclass of Component class
• It has additional methods that allow other Component objects to
be nested within it
• A container is responsible for laying out any components that it
contains
• It does this through the use of various layout managers

THE CLASS HIERARCHY


PANEL

• The Panel class is a concrete subclass of Container


• It doesn’t add any new methods;
• it simply implements Container
• Panel is the superclass for Applet.
• When screen output is directed to an applet, it is
drawn on the surface of a Panel object.
• A Panel is a window that does not contain a title bar,
menu bar, or border
WINDOW

• The Window class creates a top-level window


• A top-level window is not contained within any
other object; it sits directly on the desktop
• Generally, we won’t create Window objects
directly. Instead, we will use a subclass of Window
called Frame
FRAME

• Frame encapsulates what is commonly thought of as a


“window.”
• It is a subclass of Window and has a title bar, menu
bar, borders, and resizing corners
• When a Frame window is created by a stand-alone
application rather than an applet, a normal window is
created
CANVAS

• it is not part of the hierarchy for applet or frame


windows
• Canvas encapsulates a blank window upon which
you can draw.
WORKING WITH GRAPHICS

• The Graphics class defines a number of drawing


functions
• A graphics context is encapsulated by the Graphics
class and is obtained in two ways:
• It is passed to an applet when one of its various
methods, such as paint( ) or update( ), is called.
• It is returned by the getGraphics( ) method of
Component
DRAWING LINES

• Lines are drawn by


means of the
drawLine( )
method
Syntax:
• void drawLine(int
startX, int startY,
int endX, int endY)
DRAWING
RECTANGLES
• The drawRect( )
• outlined rectangle
• void drawRect(int top,
int left, int width, int
height)
• The fillRect( )
• filled rectangle
• void fillRect(int top, int
left, int width, int height)
• The upper-left corner
of the rectangle is at
top,left.
DRAWING ELLIPSES
AND CIRCLES
• drawOval( )
• void drawOval(int
top, int left, int
width, int height)
• fillOval( )
• void fillOval(int top,
int left, int width, int
height)
DRAWING
POLYGONS
• drawPolygon( )
• void drawPolygon(int
x[ ], int y[ ], int
numPoints)
• fillPolygon( )
• void fillPolygon(int
x[ ], int y[ ], int
numPoints)
• The polygon’s endpoints are
specified by the coordinate
pairs contained within the x
and y arrays.
WORKING WITH COLOR

• Color is encapsulated by the Color class


• 3 commonly used forms
• Color(int red, int green, int blue)
• three integers that specify the color as a mix of red, green, and blue
• Color(int rgbValue)
• single integer that contains the mix of red, green, and blue packed into an
integer.
• Color(float red, float green, float blue)
• takes three float values (between 0.0 and 1.0) that specify the relative mix of
red, green, and blue.

• Color Methods
• void setColor(Color newColor)
• Color getColor( )
A COLOR DEMONSTRATION APPLET
import java.awt.*; g.setColor(c3);
import java.applet.*;
g.drawLine(20, 150, 400, 40);
/*< applet code="ColorDemo"
width=300 height=200 g.drawLine(5, 290, 80, 19);
</applet>*/ g.setColor(Color.red);
public class ColorDemo extends Applet g.drawOval(10, 10, 50, 50);
{
// draw lines g.fillOval(70, 90, 140, 100
public void paint(Graphics g) { g.setColor(Color.blue);
Color c1 = new Color(255, 100, 100); g.drawOval(190, 10, 90, 30);
Color c2 = new Color(100, 255, 100);
g.drawRect(10, 10, 60, 50);
Color c3 = new Color(100, 100, 255);
g.setColor(c1);
g.setColor(Color.cyan);
g.drawLine(0, 0, 100, 100); g.fillRect(100, 10, 60, 50);
g.drawLine(0, 100, 100, 0); g.drawRoundRect(190, 10, 60, 50,
g.setColor(c2); 15, 15);
g.drawLine(40, 25, 250, 180); }
g.drawLine(75, 90, 400, 400);
}
WORKING WITH FONTS

• The AWT supports multiple type fonts


• Fonts have a family name, a logical font name, and a face
name
• The family name is the general name of the font, such as Courier.
• The logical name specifies a category of font, such as Monospaced.
• The face name specifies a specific font, such as Courier Italic.
• Fonts are encapsulated by the Font class.
• Creating and Selecting a Font
• Font(String fontName, int fontStyle, int pointSize)
• fontName specifies the name of the desired font
• The style of the font is specified by fontStyle: Font.PLAIN, Font.BOLD, and
Font.ITALIC.
• The size, in points, of the font is specified by pointSize.
• To use a font that you have created, you must select it using
setFont( ):void setFont(Font fontObj)
PROGRAM FOR IMPLEMENTING FONT CLASS

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="FontClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class FontClass extends java.applet.Applet
{
Font f;
String m;
public void init()
{
f=new Font("Arial",Font.ITALIC,20);
m="Welcome to Java";
setFont(f);
}
public void paint(Graphics g)
{
Color c=new Color(0,255,0);
g.setColor(c);
g.drawString(m,4,20);
}
}
AWT CONTROLS
CONTROL FUNDAMENTALS

• The AWT supports the following types of controls:


• Labels
• Push buttons
• Check boxes
• Choice lists
• Lists
• Scroll bars
• Text editing
ADDING AND REMOVING CONTROLS

• To include a control in a window, you must add it


to the window
• first create an instance of the desired control
• add it to a window by calling add( )
• Component add(Component compObj)
• when the control is no longer needed, we can
remove it by calling remove( )
• void remove(Component obj)
LABELS

• The easiest control to use is a label.


• it contains a string, which it displays
• Label defines the following constructors:
• Label( ) : creates a blank label.
• Label(String str) : creates a label that contains
the string specified
by str
• Label(String str, int how) : creates a label that contains
the string specified
by str using the alignment
specified by how
• setText( ) : used to set or change the text in a
label
• getText( ) : can obtain the current label
DEMONSTRATING LABELS
USING BUTTONS

• A push button is a component that contains a label


and that generates an event when it is pressed
• Button defines these two constructors:
• Button( ) : creates an empty button
• Button(String str) : creates a button that contains str as a
label
• setLabel( ) : sets the label of the button
• getLabel( ) : retrive the label of the button
HANDLING BUTTONS

• Each time a button is pressed, an action event is


generated
• This is sent to any listeners
• Each listener implements the ActionListener interface
• That interface defines the actionPerformed( ) method, which is
called when an event occurs.
• getActionCommand( ):label on the button is retrived
DEMONSTRATING BUTTONS
import java.awt.*;
public void actionPerformed(ActionEvent ae)
import java.awt.event.*; {
import java.applet.*; String str = ae.getActionCommand();
/* <applet code="ButtonDemo" width=250 if(str.equals("Yes")) {
height=150>
msg = "You pressed Yes.";
</applet> */
}
public class ButtonDemo extends Applet
else if(str.equals("No")) {
implements ActionListener {
msg = "You pressed No.";
String msg = "";
Button yes, no, maybe; }
public void init() { else {
yes = new Button("Yes"); msg = "You pressed Undecided.";
no = new Button("No"); }
maybe = new Button("Undecided"); repaint();
add(yes); }
add(no); public void paint(Graphics g)
add(maybe); {
yes.addActionListener(this); g.drawString(msg, 6, 100);
no.addActionListener(this); }
maybe.addActionListener(this); }
}
o/p
APPLYING 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
• Checkbox supports these constructors
• Checkbox( ) : label is initially blank, The state of the check box is unchecked
• Checkbox(String str): label is specified by str, The state of the check box is unchecked
• Checkbox(String str, boolean on):allows to set the initial state of the check box
• Checkbox(String str, boolean on, CheckboxGroup cbGroup)
• Checkbox(String str, CheckboxGroup cbGroup, boolean on)
• group is specified by cbGroup
• getState( ): retrieve the current state of a check box
• setState( ), getLabel( ), setLabel( )


HANDLING CHECK BOXES

• Each time a check box is selected or deselected, an


item event is generated
• This is sent to any listeners
• Each listener implements the ItemListener interface.
• That interface defines the itemStateChanged( )
method
DEMONSTRATING CHECK BOXES
CHOICE CONTROLS
• The Choice class is used to create a pop-up list of items
from which the user may choose
• Choice control is a form of menu.
• When the user clicks on it, the whole list of choices
pops up

• To add a selection to the list, call add( )


• getSelectedItem( ): returns a string containing the name of
the item
• getSelectedIndex( ): returns the index of the item
• getItemCount( ): number of items in the list
• select( ) : can set the currently selected item
HANDLING CHOICE LISTS

• Each time a choice is selected, an item event is


generated
• This is sent to any listeners
• Each listener implements the ItemListener interface.
• That interface defines the itemStateChanged( )
method
DEMONSTRATING CHOICE LISTS
import java.awt.*;
import java.awt.event.*; // add items to browser list
browser.add("Internet Explorer");
import java.applet.*; browser.add("Firefox"); browser.add("Opera");
/*<applet code="ChoiceDemo" // add choice lists to window
width=300 height=180> add(os);
</applet > */ add(browser);
public class ChoiceDemo extends Applet // register to receive item events
implements ItemListener { os.addItemListener(this);
browser.addItemListener(this);
Choice os, browser; }
String msg = ""; public void itemStateChanged(ItemEvent ie) {
public void init() { repaint();
os = new Choice(); }
browser = new Choice(); // Display current selections.
public void paint(Graphics g) {
// add items to os list
msg = "Current OS: ";
os.add("Windows XP"); msg += os.getSelectedItem();
os.add("Windows Vista"); g.drawString(msg, 6, 120);
os.add("Solaris"); msg = "Current Browser: ";
os.add("Mac OS"); msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}}
USING LISTS
• The List class provides a compact, multiple-choice,
scrolling selection list
• a List object can be constructed to show any number of
choices in the visible window

• List provides these constructors:


• List( ) throws HeadlessException :allows only one item to be
selected
• List(int numRows) throws HeadlessException: number of entries in
the list
• List(int numRows, boolean multipleSelect) throws
HANDLING LISTS

• To add a selection to the list, call add( ).


• void add(String name) : Here, name is the name of the item
added to the list.
• void add(String name, int index) : adds the item at the index
specified by index

• item is selected by calling


• getSelectedItem( ) - getSelectedItems( )
• getSelectedIndex( ) - getSelectedIndexes( )
• getItemCount( )
• select(int index)
DEMO PROGRAM
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ListDemo" width=300 height=180> </applet >
*/
public class ListDemo extends Applet implements ActionListener {
List os, browser;
String msg = "";
public void init() {
os = new List(4, true);
browser = new List(4, false);
// add items to os list
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
browser.select(1);
// add lists to window
add(os);
add(browser);
// register to receive action events
os.addActionListener(this);
browser.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
// Display current selections.
public void paint(Graphics g)
{
int idx[];
msg = "Current OS: ";
idx = os.getSelectedIndexes();
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + " ";
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
} }
O/P
MANAGING SCROLL BARS

• Scroll bars are used to select continuous values between a


specified minimum and maximum
• It may be oriented horizontally or vertically.
• Scrollbar defines the following constructors:
• Scrollbar( ) :creates a vertical scroll bar
• Scrollbar(int style)
• If style is Scrollbar.VERTICAL, a vertical scroll bar is created.
• If style is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
• Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
• the initial value of the scroll bar is passed in initialValue.
• The minimum and maximum values for the scroll bar are specified by
min and max
• The number of units represented by the height of the thumb is passed
in thumbSize.
• current value of the scroll bar, call getValue( ).
• To set the current value, call setValue( ).
USING A TEXTFIELD

• implements a single-line text-entry area


• TextField is a subclass of TextComponent
• TextField defines the following constructors:
• TextField( ) :creates a default text field
• TextField(int numChars) :creates a text field that is numChars characters
wide
• TextField(String str) :initializes the text field with the string
• TextField(String str, int numChars): both the above 2
• getText( ), setText( ), getSelectedText( )
• select(int startIndex, int endIndex)
• boolean isEditable( ) returns true if the text may be
changed
• void setEditable(boolean canEdit):if canEdit is true, the
text may be changed.
HANDLING A TEXTFIELD

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="TextFieldDemo" width=300 height=180>
</applet > */
public class TextFieldDemo extends Applet implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep); add(name); add(passp); add(pass);
// register to receive action events
name.addActionListener(this); pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g)
{
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: " +
name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}
}
USING A TEXTAREA

• AWT includes a simple multiline editor called TextArea


• Following are the constructors for TextArea:
• TextArea( )
• TextArea(int numLines, int numChars)
• TextArea(String str)
• TextArea(String str, int numLines, int numChars)
• TextArea(String str, int numLines, int numChars, int sBars)
• numLines specifies the height, in lines
• numChars specifies its width
• Initial text can be specified by str
• can specify the scroll bars by
• SCROLLBARS_BOTH, SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_NONE
• void append(String str) void insert(String str, int index)
• void replaceRange(String str, int startIndex, int
endIndex)
LAYOUT MANAGERS

• All of the components are positioned by the default


layout manager
• a layout manager automatically arranges your controls
within a window by using some type of algorithm
• Each Container object has a layout manager associated
with it
• The layout manager is set by the setLayout( ) method
FLOWLAYOUT
• FlowLayout is the default layout manager
• FlowLayout implements a simple layout style, which is similar
to how words flow in a text editor
• by default, is left to right, top to bottom.
• the constructors for FlowLayout:
• FlowLayout( )
• centers components and leaves five pixels of space between each component
• FlowLayout(int how)
• specify how each line is aligned.
• Valid values for how are as follows:
• FlowLayout.LEFT
• FlowLayout.CENTER
• FlowLayout.RIGHT
• FlowLayout.LEADING
• FlowLayout.TRAILING
• FlowLayout(int how, int horz, int vert)
• allows us to specify the horizontal and vertical space left between components
BORDERLAYOUT

• The BorderLayout class implements a common layout


style for top-level windows
• It has four narrow, fixed-width components at the edges
and one large area in the center.
• The four sides are referred to as north, south, east, &
west.
• The middle area is called the center
GRIDLAYOUT

• GridLayout lays out components in a 2D grid


• When we instantiate a GridLayout, we define the
number of rows and columns.
CARDLAYOUT

• it stores several different layouts


• The cards are typically held in an object of type Panel
• This panel must have CardLayout selected as its layout
manager.
MENU BARS AND MENUS

• A top-level window can have a menu bar associated with it


• A menu bar displays a list of top-level menu choices.
• Each choice is associated with a drop-down menu
• implemented in the AWT by the following classes:
• MenuBar, Menu, and MenuItem
• a menu bar contains one or more Menu objects
• Each Menu object contains a list of MenuItem objects
• Each MenuItem object represents something that can
be selected by the user
• It is also possible to include checkable menu items
• These are menu options of type CheckboxMenuItem and will
have a check mark next to them when they are selected
• constructors for Menu:
• Menu( ) throws HeadlessException
• Menu(String optionName) throws HeadlessException
• optionName specifies the name of the menu selection.
• Menu(String optionName, boolean removable) throws
HeadlessException
• If removable is true, the menu can be removed and allowed to float
free
• Otherwise, it will remain attached to the menu bar.
• Individual menu items are of type MenuItem.
• It defines these constructors:
• MenuItem( ) throws HeadlessException
• MenuItem(String itemName) throws HeadlessException
• itemName is the name shown in the menu
• MenuItem(String itemName, MenuShortcut keyAccel)
throws HeadlessException
• keyAccel is the menu shortcut for this item
METHODS

Method Description
setEnabled( ) can disable or enable a menu item
isEnabled( ) determines an item’s status
setLabel( ) change the name of a menu item
getLabel( ) retrieve the current name of the menu item
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}

You might also like