Javatpoint Logo
Javatpoint Logo

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 ClassesListener Interfaces
ActionEventActionListener
MouseEventMouseListener and MouseMotionListener
MouseWheelEventMouseWheelListener
KeyEventKeyListener
ItemEventItemListener
TextEventTextListener
AdjustmentEventAdjustmentListener
WindowEventWindowListener
ComponentEventComponentListener
ContainerEventContainerListener
FocusEventFocusListener

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 Code

We can put the event handling code into one of the following places:

  1. Within class
  2. Other class
  3. Anonymous class

Java event handling by implementing ActionListener

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc.

event handling in java

2) Java event handling by outer class


3) Java event handling by anonymous class

Next TopicJava AWT Button





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA