Sei sulla pagina 1di 22

EVENT HANDALING PROGRAMS

Event Classes and Interface


Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu-item is ActionListener


selected, list-item,choice is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and also
when it enters or exit a component

KeyEvent generated when input is received from KeyListener


keyboard

ItemEvent generated when check-box or list item is ItemListener


clicked

TextEvent generated when value of textarea or textfield is TextListener


changed

MouseEvent generated when mouse is moved,dragged MouseMotionListener

WindowEvent generated when window is activated, WindowListener


deactivated, deiconified, iconified, opened or
closed

ComponentEvent generated when component is hidden, moved, ComponentEventListener


resized or set visible
ContainerEvent generated when component is added or ContainerListener
removed from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses FocusListener


keyboard focus
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o public void addActionListener(ActionListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o 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
1) Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

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

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
2) Java event handling by outer class
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
3) Java event handling by anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}

1. Java ActionListener Interface


The Java ActionListener is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in java.awt.event package. It has only
one method: actionPerformed().

actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
public abstract void actionPerformed(ActionEvent e);
 Action event Action listener program
import java.awt.*;
import java.awt.event.*;
public class large extends Frame implements ActionListener
{
Frame f=new Frame();
Label l=new Label("1st number");
Label l1=new Label("2st number");
TextField t1=new TextField(30);
TextField t2=new TextField(30);
TextField t3=new TextField(30);
Button b=new Button("LARGEST");
large(){
f.add(l);
f.add(t1);
f.add(l1);
f.add(t2);
f.add(b);
f.add(t3);
b.addActionListener(this);
//f.setLayout(new GridLayout(3,3));
f.setLayout(new FlowLayout());

f.setVisible(true);
f.setSize(500,500);
}
public void actionPerformed(ActionEvent ae)
{
int no1=Integer.parseInt(t1.getText());
int no2=Integer.parseInt(t2.getText());
if(no1>no2){
t3.setText("FIRST NUMBER is GREATER");
}
else{
t3.setText("SECOND NUMBER is GREATER");
}
}
public static void main(String args[])
{
new large();
}
}
2. Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.

Methods of MouseListener interface

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


1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
6. Java MouseMotionListener Interface

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

Methods of MouseMotionListener interface

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

1. public abstract void mouseDragged(MouseEvent e);


2. public abstract void mouseMoved(MouseEvent e);
This event indicates a mouse action occurred in a component. This low-level event is generated
by a component object for Mouse Events and Mouse motion events.
 a mouse button is pressed
 a mouse button is released
 a mouse button is clicked (pressed and released)
 a mouse cursor enters the unobscured part of component's geometry
 a mouse cursor exits the unobscured part of component's geometry
 a mouse is moved
 the mouse is dragged
Class declaration
Following is the declaration for java.awt.event.MouseEvent class:
Following is the declaration for java.awt.event.MouseEvent class:

public class MouseEvent extends InputEvent

 Mouse event and its 1 listener interface


import java.awt.*;
import java.awt.event.*;
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();
}
}

 Mouse event and its 2 listener interface


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseXY extends Applet implements MouseListener, MouseMotionListener
{
int x, y;
String str="";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);

}
// override MouseListener five abstract methods
public void mousePressed(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Released";
repaint();
}
public void mouseClicked(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Exited";
repaint();
}
// override MouseMotionListener two abstract methods
public void mouseMoved(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Moved";
repaint();
}
public void mouseDragged(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse dragged";
repaint();
}
public void paint(Graphics g)
{
// g.setFont(new Font("Monospaced", Font.BOLD, 20));
//g.fillOval(x, y, 10, 10); // gives the bullet
g.drawString(x + "," + y, x+10, y -10); // displays the x and y position
g.drawString(str, x+10, y+20); // displays the action performed
}

}
/*<applet code=MouseXY width=500 height=500></applet>*/

7. Java KeyListener Interface


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

Methods of KeyListener interface

The signature of 3 methods found in KeyListener interface are given below:

1. public abstract void keyPressed(KeyEvent e);


2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);

Class declaration
Following is the declaration for java.awt.event.KeyEvent class:

public class KeyEvent extends InputEvent

 KeyListener
import java.awt.*;
import java.awt.event.*;
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();
}
}

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="Key" width=300 height=400> </applet>*/
public class Key extends Applet implements KeyListener
{
int X=20,Y=30;
String msg="KeyEvents--->";
public void init()
{
addKeyListener(this);
requestFocus(); /*As for requestFocus(),
this method is used to make the component get input focus.
This means that if you press any kind of key or give any input, the input is heard by the
respective Listener for that component.*/
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=k.getKeyCode();//int getKeyCode():Returns the integer keyCode associated with
the key in this event.

switch(key)
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=k.getKeyChar();//char getKeyChar(): Returns the character associated with the key
in this event.

repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
8. Java ItemListener Interface
The Java ItemListener is notified whenever you click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one
method: itemStateChanged().

itemStateChanged() method

The itemStateChanged() method is invoked automatically whenever you click or unclick on the
registered checkbox component.

 ItemListerrner program

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AppletItemEvents extends Applet implements ItemListener
{
Checkbox c1,c2,r1,r2;
CheckboxGroup cbg;
Label l1,l2;
String msg1 = "", msg2 = "";
public void init()
{
l1 = new Label("Languages you know:");
l2 = new Label("Gender:");
c1 = new Checkbox("English");
c2 = new Checkbox("French");
cbg = new CheckboxGroup();
r1 = new Checkbox("Male",cbg,true);
r2 = new Checkbox("Female",cbg,false);

c1.addItemListener(this);
c2.addItemListener(this);
r1.addItemListener(this);
r2.addItemListener(this);

add(l1);
add(c1);
add(c2);
add(l2);
add(r1);
add(r2);

}
public void itemStateChanged(ItemEvent ie)
{
String t1 = c1.getState()"English ":"";
String t2 = c2.getState()"French":"";
msg1 = "Languages:" + t1 + t2 ;
String t3 = r1.getState()"Male":"Female";
msg2 = "gender:" + t3;
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg1, 50,200);
g.drawString(msg2, 50,240);
}
}
/*
<applet code="AppletItemEvents" width="300" height="300"></applet>
*/
import java.awt.*;
import java.awt.event.*;
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: "
+ (e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}
9. Java WindowListener Interface
The Java WindowListener is notified whenever you change the state of window. It is notified
against WindowEvent. The WindowListener interface is found in java.awt.event package. It has
three methods.

Methods of WindowListener interface

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

1. public abstract void windowActivated(WindowEvent e);


2. public abstract void windowClosed(WindowEvent e);
3. public abstract void windowClosing(WindowEvent e);
4. public abstract void windowDeactivated(WindowEvent e);
5. public abstract void windowDeiconified(WindowEvent e);
6. public abstract void windowIconified(WindowEvent e);
7. public abstract void windowOpened(WindowEvent e);
 Program of window listerner
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample extends Frame implements WindowListener{
WindowExample(){
addWindowListener(this);

setSize(400,400);
setLayout(null);
setVisible(true);
}

public static void main(String[] args) {


new WindowExample();
}
public void windowActivated(WindowEvent arg0) {
System.out.println("activated");
}
public void windowClosed(WindowEvent arg0) {
System.out.println("closed");
}
public void windowClosing(WindowEvent arg0) {
System.out.println("closing");
dispose();
}
public void windowDeactivated(WindowEvent arg0) {
System.out.println("deactivated");
}
public void windowDeiconified(WindowEvent arg0) {
System.out.println("deiconified");
}
public void windowIconified(WindowEvent arg0) {
System.out.println("iconified");
}
public void windowOpened(WindowEvent arg0) {
System.out.println("opened");
}
}
10. Java AdjustmentEvent
The Class AdjustmentEvent represents adjustment event emitted by Adjustable objects.
Class declaration
Following is the declaration for java.awt.event.AdjustmentEvent class:

public class AdjustmentEvent extends AWTEvent

Field
Following are the fields for java.awt.Component class:
 static int ADJUSTMENT_FIRST -- Marks the first integer id for the range of adjustment
event ids.
 static int ADJUSTMENT_LAST -- Marks the last integer id for the range of adjustment
event ids.
 static int ADJUSTMENT_VALUE_CHANGED -- The adjustment value changed event.
 static int BLOCK_DECREMENT -- The block decrement adjustment type.
 static int BLOCK_INCREMENT -- The block increment adjustment type.
 static int TRACK -- The absolute tracking adjustment type.
 static int UNIT_DECREMENT -- The unit decrement adjustment type.
 static int UNIT_INCREMENT -- The unit increment adjustment type.
Class constructors
S.N. Constructor & Description

1 AdjustmentEvent(Adjustable source, int id, int type, int value)


Constructs an AdjustmentEvent object with the specified Adjustable source, event
type, adjustment type, and value.

2 AdjustmentEvent(Adjustable source, int id, int type, int value, boolean


isAdjusting)
Constructs an AdjustmentEvent object with the specified Adjustable source, event
type, adjustment type, and value.
Class methods
S.N. Method & Description

1 Adjustable getAdjustable()
Returns the Adjustable object where this event originated.

2 int getAdjustmentType()
Returns the type of adjustment which caused the value changed event.
3 int getValue()
Returns the current value in the adjustment event.

4 boolean getValueIsAdjusting()
Returns true if this is one of multiple adjustment events.

5 String paramString()
Returns a string representing the state of this Event.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=AScrollbar width=500 height=500></applet>*/
public class AScrollbar extends Applet implements AdjustmentListener {
public void init() {
scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, 50, 0, 0, 100);
add(scrollbar);
scrollbar.addAdjustmentListener(this);
textField = new TextField(3);
textField.setEditable(false);
add(textField);
}

public void adjustmentValueChanged(AdjustmentEvent e) {


textField.setText(scrollbar.getValue()+"");
}

Scrollbar scrollbar;
TextField textField;
}

/*Scrollbar():Constructs a new vertical scroll bar.


Scrollbar(int orientation):Constructs a new scroll bar with the specified orientation.

Scrollbar(int orientation, int value, int visible, int minimum, int maximum)
Constructs a new scroll bar with the specified orientation, initial value, visible amount, and
minimum and maximum values.
*/

import java.awt.*;
import java.awt.event.*;
class MyScroll extends Frame implements AdjustmentListener
{
Scrollbar scr_red,scr_green,scr_blue;
int r,g,b;
public MyScroll()
{
setTitle("Scrollbar");
setSize(500,500);
setLocation(100,100);

scr_red=new Scrollbar(Scrollbar.HORIZONTAL,0,45,0,300);
scr_green=new Scrollbar(Scrollbar.HORIZONTAL,0,45,0,300);
scr_blue=new Scrollbar(Scrollbar.HORIZONTAL,0,45,0,300);

scr_red.addAdjustmentListener(this);
scr_green.addAdjustmentListener(this);
scr_blue.addAdjustmentListener(this);

setLayout(null);
//setLayout(new FlowLayout());
setVisible(true);
scr_red.setBounds(10,50,200,20);
scr_green.setBounds(10,80,200,20);
scr_blue.setBounds(10,110,200,20);

add(scr_red);
add(scr_green);
add(scr_blue);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
if(ae.getSource()==scr_red)
{
r=scr_red.getValue();
}
else if(ae.getSource()==scr_green)
{
g=scr_green.getValue();
}
else if(ae.getSource()==scr_blue)
{
b=scr_blue.getValue();
}
setBackground(new Color(r,g,b));
}
public static void main(String []args)
{
new MyScroll();
}
}
Go through this link for more details
https://www.decodejava.com/java-events.htm
11. Java TextListener
The class which processes the TextEvent should implement this interface.The object of that
class must be registered with a component. The object can be registered using the
addTextListener() method.
Interface declaration
Following is the declaration for java.awt.event.TextListener interface:

public interface TextListener extends EventListener

Interface methods
S.N. Method & Description

1 void textValueChanged(TextEvent e)
Invoked when the value of the text has changed.
import java.awt.*;
import java.awt.event.*;

public class TextEventEx1 implements TextListener


{
Label label1, label2;
TextField field1;
Frame jf;
String str;

TextEventEx1()
{

jf = new Frame("Handling TextEvent");

label1= new Label("Type in the textfield, to see the textevents it generates -", Label.CENTER);
label2= new Label();
field1 = new TextField(25);

jf.setLayout(new FlowLayout());

jf.add(label1);
jf.add(field1);
jf.add(label2);

//Registering the class TextEventEx1 to catch and respond to mouse text events
field1.addTextListener(this);
jf.setSize(340,200);
jf.setVisible(true);
}

public void textValueChanged(TextEvent te)


{
label2.setText(te.paramString());
jf.setVisible(true);
}

public static void main(String... ar)


{
new TextEventEx1();
}
}
12. ComponentEvent
The class which processes the ComponentEvent should implement this interface.The object of
that class must be registered with a component. The object can be registered using the
addComponentListener() method. Component event are raised for information only.
Interface declaration
Following is the declaration for java.awt.event.ComponentListenerinterface:

public interface ComponentListener extends EventListener

Interface methods
S.N. Method & Description

1 void componentHidden(ComponentEvent e)
Invoked when the component has been made invisible.

2 void componentMoved(ComponentEvent e)
Invoked when the component's position changes.

3 void componentResized(ComponentEvent e)
Invoked when the component's size changes.

4 void componentShown(ComponentEvent e)
Invoked when the component has been made visible.
import java.awt.*;
import java.awt.event.*;
public class Example extends Frame implements ComponentListener {
public static void main(String args[]) {

Frame f = new Frame();

public void componentHidden(ComponentEvent event) {

dump("Hidden", event);

public void componentMoved(ComponentEvent event) {

dump("Moved", event);

public void componentResized(ComponentEvent event) {

dump("Resized", event);

public void componentShown(ComponentEvent event) {

dump("Shown", event);

Public void dump(String str, ComponentEvent event) {

System.out.println(event.getComponent().getName() + " : " + str);

};

JButton lbutton = new JButton("Left");

lbutton.setName("Left");

lbutton.addComponentListener(this);

final JButton lright = new JButton("Right");


lright.setName("Right");

lright.addComponentListener(this);

ActionListener action = new ActionListener() {

public void actionPerformed(ActionEvent event) {

lright.setVisible(!lright.isVisible());

};

lbutton.addActionListener(action);

JSplitPane splitBar = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,

lbutton, lright);

cPane.add(splitBar, BorderLayout.CENTER);

f.setSize(500, 400);

f.setVisible(true);
}
}

Potrebbero piacerti anche