Event and Listener – Java Swing – Example
In this tutorial, we are going to see an example of events and listeners in Java Swing. Changing the state of an object is called an event. For example, click the button, drag the mouse, etc. java.awt.event package provides many Event classes and Listeners interfaces for handling events.
Events classes and Listeners interfaces
ActionEvent | ActionListener | This interface is used to receive action events. |
MouseEvent | MouseListener and MouseMotionListener | This interface is used to receive mouse events. |
KeyEvent | KeyListener | This interface is used to receive events from the keys. |
ItemEvent | ItemListener | This interface is used to receive element events. |
TextEvent | TextListener | This interface is used to receive text events. |
AdjustmentEvent | AdjustmentListener | This interface is used to receive adjustment events. |
WindowEvent | WindowListener | This interface is used to receive events from the window object. |
ComponentEvent | ComponentListener | This interface is used to receive events from components. |
ContainerEvent | ContainerListener | This interface is used to receive container events. |
[st_adsense]
Event Management:
The following steps are required to manage an event:
– Register the Listener to a component.
To register a Listener on a component, many classes provide the registration methods. For example:
- Button Class: public void addActionListener(ActionListener a){}
- TextArea Class: public void addTextListener(TextListener a){}
- Checkbox Class: public void addItemListener(ItemListener a){}
- MenuItem Class: public void addActionListener(ActionListener a){}
- TextField Class: public void addTextListener(TextListener a){}
[st_adsense]
Example : ActionListener in Java Swing
import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; //1st step: Implement ActionListener interface public class MyJButtonActionListener implements ActionListener { private static JTextField text; public static void main(String[] args) { JFrame frame = new JFrame("ActionListener Example"); text = new JTextField(); text.setBounds(45,50,150,20); JButton btn = new JButton("Click here"); btn.setBounds(70,100,100,30); MyJButtonActionListener instance = new MyJButtonActionListener(); //2nd step: Register the component with the Listener btn.addActionListener(instance); frame.add(btn); frame.add(text); frame.setSize(250,250); frame.setLayout(null); frame.setVisible(true); } //3rd step: Override the method actionPerformed() public void actionPerformed(ActionEvent e){ text.setText("Welcome to StackHowTo"); } }
Output:
[st_adsense]