This section contains the detail about the EventListener Interfaces in java.
EventListener Interfaces
An event listener registers with an event source to receive notifications
about the events of a particular type.
Various event listener interfaces defined in the java.awt.event
package
are given below :
Interface | Description |
ActionListener | Defines the actionPerformed() method to receive and process action events. |
MouseListener | Defines five methods to receive mouse events, such as when a mouse is clicked, pressed, released, enters, or exits a component |
MouseMotionListener | Defines two methods to receive events, such as when a mouse is dragged or moved. |
AdjustmentListner | Defines the adjustmentValueChanged() method to receive and process the adjustment events. |
TextListener | Defines the textValueChanged() method to receive and process an event when the text value changes. |
WindowListener | Defines seven window methods to receive events. |
ItemListener | Defines the itemStateChanged() method when an item has been selected or deselected by the user. |
Example :
The following code shows the generation of an action event and its handling by the ActionListener interface :
package corejava; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ActionListenerDemo extends JFrame implements ActionListener { JButton b1, b2; JLabel lbl; int clicked; final String str = " Number of times button clicked = "; public ActionListenerDemo(String strName) { super(strName); getContentPane().setLayout(new FlowLayout()); JPanel p = new JPanel(); b1 = new JButton("Click Me"); b2 = new JButton("Quit"); p.setLayout(new FlowLayout()); p.add(b1); p.add(b2); lbl = new JLabel(str + clicked, JLabel.CENTER); getContentPane().add(p); getContentPane().add(lbl); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String s = ae.getActionCommand(); if ("Click Me".equals(s)) { clicked++; lbl.setText(str + clicked); } if ("Quit".equals(s)) { System.exit(0); } } public static void main(String args[]) { ActionListenerDemo t = new ActionListenerDemo("Action Events"); t.setSize(300, 300); t.setVisible(true); } }
Output :
It will display the number of time you clicked "Click Me" button :
[ 0 ] Comments