by Dinesh Thakur Category: Swing

Event: An event is a signal to the program that something has happened. It can be triggered by typing in a text field, selecting an item from the menu etc. The action is initiated outside the scope of the program and it is handled by a piece of code inside the program. Events may also be triggered when timer expires, hardware or software failure occurs, operation completes, counter is increased or decreased by a value etc.

Event handler: The code that performs a task in response to an event. is called event handler.

Event handling: It is process of responding to events that can occur at any time during execution of a program.

Event Source: It is an object that generates the event(s). Usually the event source is a button or the other component that the user can click but any Swing component can be an event source. The job of the event source is to accept registrations, get events from the user and call the listener's event handling method.

Event Listener: It is an object that watch for (i.e. listen for) events and handles them when they occur. It is basically a consumer that receives events from the source. To sum up, the job of an event listener is to implement the interface, register with the source and provide the eventhandling.

Listener interface: It is an interface which contains methods that the listener must implement and the source of the event invokes when the event occurs.

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
class EventExample extends JFrame implements ActionListener
{
    private int count =0;
    JLabel lblData;
    EventExample()
    {
      setLayout(new FlowLayout());
      lblData = new JLabel("Button Clicked 0 Times");
      JButton btnClick=new JButton("Click Me");
      btnClick.addActionListener(this);
      add(lblData);
      add(btnClick);
    }
    public void actionPerformed(ActionEvent e)
    {
      count++;
      lblData.setText("Button Clicked " + count +" Times");
    }
}
  class EventHandlingJavaExample
 {
    public static void main(String args[])
    {
       EventExample frame = new EventExample();
       frame.setTitle("Event Handling Java Example");
       frame.setBounds(200,150,180,150);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setVisible(true);
    }
 }

Event Handling in Java Swing Examples



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles