0% found this document useful (0 votes)
36 views21 pages

Listeners

The document discusses Java event handling and provides details about event classes, listener interfaces, the registration process, and examples of implementing listeners for buttons and text fields. Common AWT components like buttons, labels, and text fields are also described including their constructors and methods.

Uploaded by

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

Listeners

The document discusses Java event handling and provides details about event classes, listener interfaces, the registration process, and examples of implementing listeners for buttons and text fields. Common AWT components like buttons, labels, and text fields are also described including their constructors and methods.

Uploaded by

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

Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces for
event handling.

Java Event classes and 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
ContainerEvent ContainerListener
FocusEvent FocusListener

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:

 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 by implementing ActionListener


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
14. b.addActionListener(this);//passing current instance
15.
16. //add components and set size, layout and visibility
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
27. }
28. }

Button Class Constructors


Following table shows the types of Button class constructors
Sr. no. Constructor Description
1. Button( ) It constructs a new button with an empty string i.e. it has no label.
2. Button (String text) It constructs a new button with given string as its label.

Button Class Methods


Sr.
Method Description
no.
1. void setText (String text) It sets the string message on the button
2. String getText() It fetches the String message on the button.
3. void setLabel (String label) It sets the label of button with the specified string.
4. String getLabel() It fetches the label of the button.
5. void addNotify() It creates the peer of the button.
AccessibleContext It fetched the accessible context associated with the
6.
getAccessibleContext() button.
void It adds the specified action listener to get the action
7.
addActionListener(ActionListener l) events from the button.
It returns the command name of the action event fired
8. String getActionCommand()
by the button.
ActionListener[ ] It returns an array of all the action listeners registered
9.
getActionListeners() on the button.
It returns an array of all the objects currently registered
10. T[ ] getListeners(Class listenerType)
as FooListeners upon this Button.
11. protected String paramString() It returns the string which represents the state of button.
protected void processActionEvent It process the action events on the button by dispatching
12.
(ActionEvent e) them to a registered ActionListener object.
protected void processEvent
13. It process the events on the button
(AWTEvent e)
void removeActionListener It removes the specified action listener so that it no
14.
(ActionListener l) longer receives action events from the button.
void setActionCommand(String It sets the command name for the action event given by
15.
command) the button.

AWT Label Class Declaration


1. public class Label extends Component implements Accessible

AWT Label Fields


The java.awt.Component class has following fields:
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.
Label class Constructors
Sr.
Constructor Description
no.
1. Label() It constructs an empty label.
It constructs a label with the given string (left justified by
2. Label(String text)
default).
Label(String text, int It constructs a label with the specified string and the specified
3.
alignement) alignment.

Label Class Methods


Specified

Sr. no. Method name Description


1. void setText(String text) It sets the texts for label with the specified text.
It sets the alignment for label with the specified
2. void setAlignment(int alignment)
alignment.
3. String getText() It gets the text of the label
4. int getAlignment() It gets the current alignment of the label.
5. void addNotify() It creates the peer for the label.
AccessibleContext It gets the Accessible Context associated with the
6.
getAccessibleContext() label.
7. protected String paramString() It returns the string the state of the label.
AWT TextField Class Declaration
1. public class TextField extends TextComponent

TextField Class constructors


Sr.
Constructor Description
no.
1. TextField() It constructs a new text field component.
It constructs a new text field initialized with the given string
2. TextField(String text)
text to be displayed.
It constructs a new textfield (empty) with given number of
3. TextField(int columns)
columns.
TextField(String text, int It constructs a new text field with the given text and given
4.
columns) number of columns (width).

TextField Class Methods


Sr.
Method name Description
no.
1. void addNotify() It creates the peer of text field.
It tells whether text field has character set for echoing or
2. boolean echoCharIsSet()
not.
void
It adds the specified action listener to receive action
3. addActionListener(ActionListener
events from the text field.
l)
ActionListener[] It returns array of all action listeners registered on text
4.
getActionListeners() field.
AccessibleContext
5. It fetches the accessible context related to the text field.
getAccessibleContext()
6. int getColumns() It fetches the number of columns in text field.
7. char getEchoChar() It fetches the character that is used for echoing.
8. Dimension getMinimumSize() It fetches the minimum dimensions for the text field.
Dimension getMinimumSize(int It fetches the minimum dimensions for the text field with
9.
columns) specified number of columns.
10. Dimension getPreferredSize() It fetches the preferred size of the text field.
Dimension getPreferredSize(int It fetches the preferred size of the text field with
11.
columns) specified number of columns.
12. protected String paramString() It returns a string representing state of the text field.
protected void
It processes action events occurring in the text field by
13. processActionEvent(ActionEvent
dispatching them to a registered ActionListener object.
e)
protected void
14. It processes the event on text field.
processEvent(AWTEvent e)
void
It removes specified action listener so that it doesn't
15. removeActionListener(ActionListe
receive action events anymore.
ner l)
16. void setColumns(int columns) It sets the number of columns in text field.
17. void setEchoChar(char c) It sets the echo character for text field.
It sets the text presented by this text component to the
18. void setText(String t)
specified text.

AWT TextArea Class Declaration


1. public class TextArea extends TextComponent

Fields of TextArea Class


The fields of java.awt.TextArea class are as follows:

 static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical
scrollbars.
 static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the
horizontal scrollbar.
 static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the vertical
scrollbar.
 static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text
area.

Class constructors:
Sr.
Constructor Description
no.
1. TextArea() It constructs a new and empty text area with no text in it.
It constructs a new text area with specified number of rows
2. TextArea (int row, int column)
and columns and empty string as text.
It constructs a new text area and displays the specified text
3. TextArea (String text)
in it.
TextArea (String text, int row, It constructs a new text area with the specified text in the
4.
int column) text area and specified number of rows and columns.
TextArea (String text, int row, It construcst a new text area with specified text in text area
5.
int column, int scrollbars) and specified number of rows and columns and visibility.

TetArea Class Methods


Sr.
Method name Description
no.
1. void addNotify() It creates a peer of text area.
It appends the specified text to the current text of text
2. void append(String str)
area.
AccessibleContext
3. It returns the accessible context related to the text area
getAccessibleContext()
4. int getColumns() It returns the number of columns of text area.
5. Dimension getMinimumSize() It determines the minimum size of a text area.
Dimension getMinimumSize(int It determines the minimum size of a text area with the
6.
rows, int columns) given number of rows and columns.
7. Dimension getPreferredSize() It determines the preferred size of a text area.
Dimension preferredSize(int rows, It determines the preferred size of a text area with
8.
int columns) given number of rows and columns.
9. int getRows() It returns the number of rows of text area.
It returns an enumerated value that indicates which
10. int getScrollbarVisibility()
scroll bars the text area uses.
It inserts the specified text at the specified position in
11. void insert(String str, int pos)
this text area.
It returns a string representing the state of this
12. protected String paramString()
TextArea.
void replaceRange(String str, int It replaces text between the indicated start and end
13.
start, int end) positions with the specified replacement text.
14. void setColumns(int columns) It sets the number of columns for this text area.
15. void setRows(int rows) It sets the number of rows for this text area.

Java AWT Checkbox


The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".

AWT Checkbox Class Declaration


1. public class Checkbox extends Component implements ItemSelectable, Accessible

Checkbox Class Constructors


Sr.
Constructor Description
no.
1. Checkbox() It constructs a checkbox with no string as the label.
2. Checkbox(String label) It constructs a checkbox with the given label.
Checkbox(String label, boolean It constructs a checkbox with the given label and sets
3.
state) the given state.
Checkbox(String label, boolean It constructs a checkbox with the given label, set the
4.
state, CheckboxGroup group) given state in the specified checkbox group.
Checkbox(String label,
It constructs a checkbox with the given label, in the
5. CheckboxGroup group, boolean
given checkbox group and set to the specified state.
state)
Method inherited by Checkbox
The methods of Checkbox class are inherited by following classes:

 java.awt.Component
 java.lang.Object

Checkbox Class Methods


Sr.
Method name Description
no.
void
It adds the given item listener to get the item events from
1. addItemListener(ItemListener
the checkbox.
IL)
AccessibleContext
2. It fetches the accessible context of checkbox.
getAccessibleContext()
3. void addNotify() It creates the peer of checkbox.
CheckboxGroup
4. It determines the group of checkbox.
getCheckboxGroup()
ItemListener[] It returns an array of the item listeners registered on
5.
getItemListeners() checkbox.
6. String getLabel() It fetched the label of checkbox.
T[] getListeners(Class It returns an array of all the objects registered as
7.
listenerType) FooListeners.
It returns an array (size 1) containing checkbox label and
8. Object[] getSelectedObjects()
returns null if checkbox is not selected.
9. boolean getState() It returns true if the checkbox is on, else returns off.
10. protected String paramString() It returns a string representing the state of checkbox.
protected void
11. It processes the event on checkbox.
processEvent(AWTEvent e)
protected void It process the item events occurring in the checkbox by
12.
processItemEvent(ItemEvent e) dispatching them to registered ItemListener object.
void It removes the specified item listener so that the item
13. removeItemListener(ItemListene listener doesn't receive item events from the checkbox
r l) anymore.
void
14. setCheckboxGroup(CheckboxGr It sets the checkbox's group to the given checkbox.
oup g)
15. void setLabel(String label) It sets the checkbox's label to the string argument.
16. void setState(boolean state) It sets the state of checkbox to the specified state.
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time
only one check box button is allowed to be in "on" state and remaining check box button in
"off" state. It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control
for creating radio buttons in AWT.

AWT CheckboxGroup Class Declaration


1. public class CheckboxGroup extends Object implements Serializable

Java AWT CheckboxGroup Example


1. import java.awt.*;
2. public class CheckboxGroupExample
3. {
4. CheckboxGroupExample(){
5. Frame f= new Frame("CheckboxGroup Example");
6. CheckboxGroup cbg = new CheckboxGroup();
7. Checkbox checkBox1 = new Checkbox("C++", cbg, false);
8. checkBox1.setBounds(100,100, 50,50);
9. Checkbox checkBox2 = new Checkbox("Java", cbg, true);
10. checkBox2.setBounds(100,150, 50,50);
11. f.add(checkBox1);
12. f.add(checkBox2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String args[])
18. {
19. new CheckboxGroupExample();
20. }
21. }

Java AWT Choice


The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration


1. public class Choice extends Component implements ItemSelectable, Accessible

Choice Class constructor


Sr. no. Constructor Description
1. Choice() It constructs a new choice menu.
Methods inherited by class
The methods of Choice class are inherited by following classes:

 java.awt.Component
 java.lang.Object

Choice Class Methods


Sr.
Method name Description
no.
1. void add(String item) It adds an item to the choice menu.
void It adds the item listener that receives item events from the
2.
addItemListener(ItemListener l) choice menu.
3. void addNotify() It creates the peer of choice.
AccessibleContext
4. It gets the accessbile context related to the choice.
getAccessibleContext()
It gets the item (string) at the given index position in the
5. String getItem(int index)
choice menu.
6. int getItemCount() It returns the number of items of the choice menu.
ItemListener[]
7. It returns an array of all item listeners registered on choice.
getItemListeners()
T[] getListeners(Class Returns an array of all the objects currently registered as
8.
listenerType) FooListeners upon this Choice.
9. int getSelectedIndex() Returns the index of the currently selected item.
10. String getSelectedItem() Gets a representation of the current choice as a string.
Returns an array (length 1) containing the currently selected
11. Object[] getSelectedObjects()
item.
void insert(String item, int
12. Inserts the item into this choice at the specified position.
index)
13. protected String paramString() Returns a string representing the state of this Choice menu.
protected void
14. It processes the event on the choice.
processEvent(AWTEvent e)
protected void Processes item events occurring on this Choice menu by
15.
processItemEvent (ItemEvent e) dispatching them to any registered ItemListener objects.
It removes an item from the choice menu at the given index
16. void remove(int position)
position.
It removes the first occurrence of the item from choice
17. void remove(String item)
menu.
18. void removeAll() It removes all the items from the choice menu.
void removeItemListener It removes the mentioned item listener. Thus is doesn't
19.
(ItemListener l) receive item events from the choice menu anymore.
It changes / sets the selected item in the choice menu to the
20. void select(int pos)
item at given index position.
It changes / sets the selected item in the choice menu to the
21. void select(String str) item whose string value is equal to string specified in the
argument.

// importing awt class


1. import java.awt.*;
2. public class ChoiceExample1 {
3.
4. // class constructor
5. ChoiceExample1() {
6.
7. // creating a frame
8. Frame f = new Frame();
9.
10. // creating a choice component
11. Choice c = new Choice();
12.
13. // setting the bounds of choice menu
14. c.setBounds(100, 100, 75, 75);
15.
16. // adding items to the choice menu
17. c.add("Item 1");
18. c.add("Item 2");
19. c.add("Item 3");
20. c.add("Item 4");
21. c.add("Item 5");
22.
23. // adding choice menu to frame
24. f.add(c);
25.
26. // setting size, layout and visibility of frame
27. f.setSize(400, 400);
28. f.setLayout(null);
29. f.setVisible(true);
30. }
31.
32. // main method
33. public static void main(String args[])
34. {
35. new ChoiceExample1();
36. }
37. }
Java AWT List
The object of List class represents a list of text items. With the help of the List class, user can
choose either one item or multiple items. It inherits the Component class.

AWT List class Declaration


1. public class List extends Component implements ItemSelectable, Accessible

AWT List Class Constructors


Sr.
Constructor Description
no.
1. List() It constructs a new scrolling list.
It constructs a new scrolling list initialized with the given
2. List(int row_num)
number of rows visible.
List(int row_num, Boolean It constructs a new scrolling list initialized which displays
3.
multipleMode) the given number of rows.

Methods Inherited by the List Class


The List class methods are inherited by following classes:

 java.awt.Component
 java.lang.Object

List Class Methods


Sr.
Method name Description
no.
1. void add(String item) It adds the specified item into the end of scrolling list.
It adds the specified item into list at the given index
2. void add(String item, int index)
position.
void
It adds the specified action listener to receive action
3. addActionListener(ActionListener
events from list.
l)
void addItemListener(ItemListener It adds specified item listener to receive item events
4.
l) from list.
5. void addNotify() It creates peer of list.
6. void deselect(int index) It deselects the item at given index position.
AccessibleContext
7. It fetches the accessible context related to the list.
getAccessibleContext()
ActionListener[] It returns an array of action listeners registered on the
8.
getActionListeners() list.
9. String getItem(int index) It fetches the item related to given index position.
10. int getItemCount() It gets the count/number of items in the list.
11. ItemListener[] getItemListeners() It returns an array of item listeners registered on the list.
12. String[] getItems() It fetched the items from the list.
13. Dimension getMinimumSize() It gets the minimum size of a scrolling list.
Dimension getMinimumSize(int It gets the minimum size of a list with given number of
14.
rows) rows.
15. Dimension getPreferredSize() It gets the preferred size of list.
Dimension getPreferredSize(int It gets the preferred size of list with given number of
16.
rows) rows.
17. int getRows() It fetches the count of visible rows in the list.
18. int getSelectedIndex() It fetches the index of selected item of list.
19. int[] getSelectedIndexes() It gets the selected indices of the list.
20. String getSelectedItem() It gets the selected item on the list.
21. String[] getSelectedItems() It gets the selected items on the list.
It gets the selected items on scrolling list in array of
22. Object[] getSelectedObjects()
objects.
It gets the index of an item which was made visible by
23. int getVisibleIndex()
method makeVisible()
24. void makeVisible(int index) It makes the item at given index visible.
25. boolean isIndexSelected(int index) It returns true if given item in the list is selected.
26. boolean isMultipleMode() It returns the true if list allows multiple selections.
It returns parameter string representing state of the
27. protected String paramString()
scrolling list.
protected void It process the action events occurring on list by
28.
processActionEvent(ActionEvent e) dispatching them to a registered ActionListener object.
protected void
29. It process the events on scrolling list.
processEvent(AWTEvent e)
protected void It process the item events occurring on list by
30.
processItemEvent(ItemEvent e) dispatching them to a registered ItemListener object.
void
It removes specified action listener. Thus it doesn't
31. removeActionListener(ActionListen
receive further action events from the list.
er l)
void It removes specified item listener. Thus it doesn't
32.
removeItemListener(ItemListener l) receive further action events from the list.
33. void remove(int position) It removes the item at given index position from the list.
34. void remove(String item) It removes the first occurrence of an item from list.
35. void removeAll() It removes all the items from the list.
void replaceItem(String newVal, int It replaces the item at the given index in list with the
36.
index) new string specified.
37. void select(int index) It selects the item at given index in the list.
It sets the flag which determines whether the list will
38. void setMultipleMode(boolean b)
allow multiple selection or not.
39. void removeNotify() It removes the peer of list.
// importing awt class
1. import java.awt.*;
2.
3. public class ListExample1
4. {
5. // class constructor
6. ListExample1() {
7. // creating the frame
8. Frame f = new Frame();
9. // creating the list of 5 rows
10. List l1 = new List(5);
11.
12. // setting the position of list component
13. l1.setBounds(100, 100, 75, 75);
14.
15. // adding list items into the list
16. l1.add("Item 1");
17. l1.add("Item 2");
18. l1.add("Item 3");
19. l1.add("Item 4");
20. l1.add("Item 5");
21.
22. // adding the list to frame
23. f.add(l1);
24.
25. // setting size, layout and visibility of frame
26. f.setSize(400, 400);
27. f.setLayout(null);
28. f.setVisible(true);
29. }
30.
31. // main method
32. public static void main(String args[])
33. {
34. new ListExample1();
35. }
36. }
Java AWT Canvas
The Canvas class controls and represents a blank rectangular area where the application can draw or
trap input events from the user. It inherits the Component class.

AWT Canvas class Declaration


1. public class Canvas extends Component implements Accessible

Canvas Class Constructors


Sr.
Constructor Description
no.
1. Canvas() It constructs a new Canvas.
Canvas(GraphicConfiguration It constructs a new Canvas with the given Graphic
2.
config) Configuration object.

Class methods
Sr.
Method name Description
no.
1. void addNotify() It creates the canvas's peer.
void createBufferStrategy (int It creates a new multi buffering strategies on the
2.
numBuffers) particular component.
It creates a new multi buffering strategies on the
void createBufferStrategy (int
3. particular component with the given buffer
numBuffers, BufferCapabilities caps)
capabilities.
AccessibleContext
4. It gets the accessible context related to the Canvas.
getAccessibleContext()
It returns the buffer strategy used by the particular
5. BufferStrategy getBufferStrategy()
component.
6. void paint(Graphics g) It paints the canvas with given Graphics object.
7. void pdate(Graphics g) It updates the canvas with given Graphics object.

// importing awt class


1. import java.awt.*;
2.
3. // class to construct a frame and containing main method
4. public class CanvasExample
5. {
6. // class constructor
7. public CanvasExample()
8. {
9.
10. // creating a frame
11. Frame f = new Frame("Canvas Example");
12. // adding canvas to frame
13. f.add(new MyCanvas());
14.
15. // setting layout, size and visibility of frame
16. f.setLayout(null);
17. f.setSize(400, 400);
18. f.setVisible(true);
19. }
20.
21. // main method
22. public static void main(String args[])
23. {
24. new CanvasExample();
25. }
26. }
27.
28. // class which inherits the Canvas class
29. // to create Canvas
30. class MyCanvas extends Canvas
31. {
32. // class constructor
33. public MyCanvas() {
34. setBackground (Color.GRAY);
35. setSize(300, 200);
36. }
37.
38. // paint() method to draw inside the canvas
39. public void paint(Graphics g)
40. {
41.
42. // adding specifications
43. g.setColor(Color.red);
44. g.fillOval(75, 75, 150, 75);
45. }
46. }

Java AWT Panel


The Panel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the Container class.
It doesn't have title bar.

AWT Panel class declaration


1. public class Panel extends Container implements Accessible
Java AWT Panel Example
1. import java.awt.*;
2. public class PanelExample {
3. PanelExample()
4. {
5. Frame f= new Frame("Panel Example");
6. Panel panel=new Panel();
7. panel.setBounds(40,80,200,200);
8. panel.setBackground(Color.gray);
9. Button b1=new Button("Button 1");
10. b1.setBounds(50,100,80,30);
11. b1.setBackground(Color.yellow);
12. Button b2=new Button("Button 2");
13. b2.setBounds(100,100,80,30);
14. b2.setBackground(Color.green);
15. panel.add(b1); panel.add(b2);
16. f.add(panel);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String args[])
22. {
23. new PanelExample();
24. }
25. }

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.
1. public abstract void actionPerformed(ActionEvent e);
How to write ActionListener
The common approach is to implement the ActionListener. If you implement the ActionListener
class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:

1. public class ActionListenerExample Implements ActionListener


2) Register the component with the Listener:
1. component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
1. public void actionPerformed(ActionEvent e){
2. //Write the code here
3. }

Java ActionListener Example: On Button click


1. import java.awt.*;
2. import java.awt.event.*;
3. //1st step
4. public class ActionListenerExample implements ActionListener{
5. public static void main(String[] args) {
6. Frame f=new Frame("ActionListener Example");
7. final TextField tf=new TextField();
8. tf.setBounds(50,50, 150,20);
9. Button b=new Button("Click Here");
10. b.setBounds(50,100,60,30);
11. //2nd step
12. b.addActionListener(this);
13. f.add(b);f.add(tf);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. //3rd step
19. public void actionPerformed(ActionEvent e){
20. tf.setText("Welcome to Javatpoint.");
21. }
22. }

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);

Java MouseListener Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }

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);

Java MouseMotionListener Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionListenerExample extends Frame implements MouseMotionListen
er{
4. MouseMotionListenerExample(){
5. addMouseMotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),20,20);
15. }
16. public void mouseMoved(MouseEvent e) {}
17.
18. public static void main(String[] args) {
19. new MouseMotionListenerExample();
20. }
21. }

You might also like