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

Unit - 3

1. Event handling in Java involves registering event sources like buttons and checkboxes with listener interfaces that define callback methods for different event types. 2. The java.awt.event package provides classes for common event types like ActionEvent and MouseEvent as well as listener interfaces like ActionListener and MouseListener. 3. Event handling code can be placed within the class, in a separate class, or as an anonymous class. This code defines what should happen in response to events being fired from sources.

Uploaded by

saturo3011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views28 pages

Unit - 3

1. Event handling in Java involves registering event sources like buttons and checkboxes with listener interfaces that define callback methods for different event types. 2. The java.awt.event package provides classes for common event types like ActionEvent and MouseEvent as well as listener interfaces like ActionListener and MouseListener. 3. Event handling code can be placed within the class, in a separate class, or as an anonymous class. This code defines what should happen in response to events being fired from sources.

Uploaded by

saturo3011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

3.

Event handling

Mundhe Shankar Gangadharrao


Lect In Information Technology
Government Polytechnic Nanded
• An event can be defined as changing the state of an object or behavior by
performing actions.
• Actions can be a button click, cursor movement, keypress or page scrolling etc.
• The java.awt.event package can be used to provide various event classes.

• 1. Foreground Events
• Foreground events are the events that require user interaction to generate
• 2. Background Events
• Events that don’t require interactions of users to generate are known as
background events.
• Eg. operating system failures/interrupts, operation completion, etc.
• Event Handling
• It is a mechanism to control the events and to decide what should happen
after an event occur.
• To handle the events, Java follows the Delegation Event model.

• Source: Events are generated from the source.


– E.g buttons, checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc.
• Listeners: Listeners are used for handling the events generated from the
source.
• Each of these listeners represents interfaces that are responsible for handling
events.
• To perform Event Handling, we need to register the source with the listener.
• Java adapter classes provide the default
implementation of listener interfaces.
• If you inherit the adapter class, you will not
be forced to provide the implementation of all
the methods of listener interfaces.
Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
FocusEvent FocusListener
Event Classes Listener Interfaces

HierarchyEvent An event which indicates a change to


the Component hierarchy to which Component belongs.
AWTEventListenerProxy A class which extends the EventListenerProxy specifically for
adding an AWTEventListener for a specific event mask.

ComponentAdapter An abstract adapter class for receiving component events.

FocusAdapter An abstract adapter class for receiving keyboard focus events.


HierarchyBoundsAdapter An abstract adapter class for receiving ancestor moved and
resized events.
InputEvent The root event class for all component-level input events.
InputMethodEvent Input method events contain information about text that is
being composed using an input method.
KeyAdapter An abstract adapter class for receiving keyboard events.

MouseAdapter An abstract adapter class for receiving mouse events.


MouseMotionAdapter An abstract adapter class for receiving mouse motion events.

PaintEvent The component-level paint event.


WindowAdapter An abstract adapter class for receiving window events.
Listener Interface Methods

ActionListener •actionPerformed()

AdjustmentListener •adjustmentValueChanged()

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

ContainerListener •componentAdded(), componentRemoved()

FocusListener •focusGained(), focusLost()

ItemListener •itemStateChanged()

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

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

MouseMotionListener •mouseMoved(), mouseDragged()

MouseWheelListener •mouseWheelMoved()

TextListener •textChanged()

•windowActivated(), windowDeactivated(), windowOpened(), windowClosed()


WindowListener
•windowClosing(), windowIconified(), windowDeiconified()
• Listener registration methods

• Button
– public void addActionListener(ActionListener a){}
• MenuItem
– public void addActionListener(ActionListener a){}
• TextField
– public void addActionListener(ActionListener a){}
– public void addTextListener(TextListener a){}
• TextArea
– public void addTextListener(TextListener a){}
• Checkbox
– public void addItemListener(ItemListener a){}
• Choice
– public void addItemListener(ItemListener a){}
• List
– public void addActionListener(ActionListener a){}
– public void addItemListener(ItemListener a){}
Java Event Handling Code
• We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
Within a class
import java.awt.*;
import java.awt.event.*;

class AEvent extends Frame implements ActionListener {


TextField tf;

AEvent() {
tf = new TextField();
tf.setBounds(60, 50, 170, 20);
Button b = new Button("Click me");
b.setBounds(100, 120, 80, 30);

b.addActionListener(this);// passing current instance

add(b);
add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


tf.setText("Button Click me Pressed");
}
public static void main(String args[]) { new AEvent(); }
}
2) Java event handling by outer class
import java.awt.*; import java.awt.event.*;
import java.awt.event.*; class Outer implements ActionListener{
class AEvent2 extends Frame{ AEvent2 obj;
TextField tf; Outer(AEvent2 obj){
AEvent2(){ this.obj=obj;
}
tf=new TextField(); public void actionPerformed(ActionEvent e){
tf.setBounds(60,50,170,20);
obj.tf.setText("welcome");
}
Button b=new Button("click me");
}
b.setBounds(100,120,80,30);
Outer o=new Outer(this); //register listener
b.addActionListener(o);
//passing outer class instance
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2(); }
}
• A nested class that doesn't have any name is known as an anonymous class.
ItemListener
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2; Label label;
ItemListenerExample(){
Frame f= new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
checkBox1.addItemListener(this); checkBox2.addItemListener(this);
f.setSize(400,400); f.setLayout(null); f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox clicked”);
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: clicked “);
}
public static void main(String args[]) { new ItemListenerExample(); }
}
KeyListener Interface
• The Java KeyListener is notified whenever you change the state of key.
• java.awt.event.KeyListener interface.

• Methods of KeyListener interface

• public abstract void keyPressed (KeyEvent e);


– It is invoked when a key has been pressed.
• public abstract void keyReleased (KeyEvent e);
– It is invoked when a key has been released.
• public abstract void keyTyped (KeyEvent e);
– It is invoked when a key has been typed.
public class KeyListenerExample extends Frame implements KeyListener {
Label l;
TextArea area;
KeyListenerExample() {
l = new Label();
l.setBounds (20, 50, 100, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize (400, 400);
setLayout (null);
setVisible (true);
}

public void keyPressed (KeyEvent e) {


l.setText ("Key Pressed");
}
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
public static void main(String[] args) { new KeyListenerExample(); }
}
MouseListener
• The Java MouseListener is notified whenever you change the state of mouse. It
is notified against MouseEvent.
• The MouseListener interface is found in java.awt.event package.

• Methods of MouseListener interface

• public abstract void mouseClicked(MouseEvent e);


• public abstract void mouseEntered(MouseEvent e);
• public abstract void mouseExited(MouseEvent e);
• public abstract void mousePressed(MouseEvent e);
• public abstract void mouseReleased(MouseEvent e);
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}

public void mouseClicked(MouseEvent e) {


l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}

public static void main(String[] args) { new MouseListenerExample(); }


}
MouseMotionListener Interface
• The Java MouseMotionListener is notified whenever you move or drag mouse.
• methods found in MouseMotionListener interface are given below:

• public abstract void mouseDragged(MouseEvent e);


• public abstract void mouseMoved(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {

Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
}

public static void main(String[] args) { new MouseMotionListenerExample(); }


}
public class MousePaint extends Frame implements MouseMotionListener {
Label l;
Color c = Color.BLUE;
MousePaint() {
l = new Label();
l.setBounds(20, 40, 100, 20);
add(l);
addMouseMotionListener(this);
setSize(400, 400);
setLayout(null);
setVisible(true);
}

public void mouseDragged(MouseEvent e) {


l.setText("X=" + e.getX() + ", Y=" + e.getY());
Graphics g = getGraphics();
g.setColor(Color.RED);
}

public void mouseMoved(MouseEvent e) {


l.setText("X=" + e.getX() + ", Y=" + e.getY());
}
public static void main(String[] args) { new MousePaint(); }
}
Java WindowListener Interface
• The declaration java.awt.event.WindowListener
• Methods of WindowListener interface

Method Description

public abstract void windowActivated (WindowEvent e); It is called when the Window is set to be an active Window.

public abstract void windowClosed (WindowEvent e); It is called when a window has been closed as the result of calling
dispose on the window.

public abstract void windowClosing (WindowEvent e); It is called when the user attempts to close the window from the
system menu of the window.

public abstract void windowDeactivated (WindowEvent e); It is called when a Window is not an active Window anymore.

public abstract void windowDeiconified (WindowEvent e); It is called when a window is changed from a minimized to a normal
state.

public abstract void windowIconified (WindowEvent e); It is called when a window is changed from a normal to a minimized
state.

public abstract void windowOpened (WindowEvent e); It is called when window is made visible for the first time.
public class WindowExample extends Frame implements WindowListener {

WindowExample() {
addWindowListener(this);
setSize (400, 400);
setLayout (null);
setVisible (true);
}
public static void main(String[] args) { new WindowExample(); }

public void windowActivated (WindowEvent arg0) { System.out.println("activated"); }

public void windowClosed (WindowEvent arg0) { System.out.println("closed"); }

public void windowClosing (WindowEvent arg0) { System.out.println("closing"); dispose(); }

public void windowDeactivated (WindowEvent arg0) { System.out.println("deactivated"); }

public void windowDeiconified (WindowEvent arg0) { System.out.println("deiconified"); }

public void windowIconified(WindowEvent arg0) { System.out.println("iconified"); }

public void windowOpened(WindowEvent arg0) { System.out.println("opened"); }


}
Inner Classes
• Java inner class or nested class is a class that is declared inside the class or
interface.
• We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
• Additionally, it can access all the members of the outer class, including private data
members and methods.
• There are two types of nested classes non-static and static nested classes. The
non-static nested classes are also known as inner classes.
– Non Static inner class
• Nested Inner Class
• Method Local Inner Classes
• Anonymous Inner Classes
– Static inner class

class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
• Advantage of Java inner classes

• Nested classes represent a particular type of relationship that is it can access


all the members (data members and methods) of the outer class, including
private.
• Nested classes are used to develop more readable and maintainable
code because it logically group classes and interfaces in one place only.

• Code Optimization: It requires less code to write.


class Outer {

class Inner {

public void show()


{
System.out.println("In a nested class method");
}
}
}

class Main {

public static void main(String[] args)


{
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
Method local Inner Class
class Outer {
void outerMethod()
{
System.out.println("inside outerMethod");
class Inner {
void innerMethod()
{
System.out.println("inside innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}

class GFG {
public static void main(String[] args)
{
Outer x = new Outer();

x.outerMethod();
}
}
• The End

You might also like