Event handling in Java explains you how to handle the external events.
Event handling in Java explains you how to handle the external events.In this section you will learn about how to handle events in Java. Events in any programming language specifies the external effects that happens and your application behaves according to that event. For example, an application produce an output when a user inputs some data, or the data received from the network or it may be something else. In Java when you works with the AWT components like button, textbox, etc (except panel, label ) generates an event. This event is handled by the listener. Event listener listens the event generated on components and performs the corresponding action.
In Java event handling may comprised the following four classes :
Example
Here I am giving a simple example which will demonstrate you about how to handle an event. In this example we will give a simple example into which you will see how an event generated after clicking on the button is handled. To handle the event you would have to implement a corresponding listener and add the listener on the component i.e. button. Then you have to override the method declared in the listener.
You can add the listener by following ways :
b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { b = (JButton)ae.getSource(); sayHi(); } });
In the second way you can add listener as follows :
b.addActionListener(this) publi void actionPerformed(ActionEvent ae){ b = (JButton)ae.getSource(); sayHi(); }
EventHandlingExample.java
import javax.swing.*; import java.awt.event.*; public class EventHandlingExample implements ActionListener{ JFrame f; JButton b=new JButton("Say Hi"); public void createUI() { f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(null); JLabel tbLabel = new JLabel("Click On Button"); b.addActionListener(this); tbLabel.setBounds(75, 50, 100, 20); b.setBounds(75,75,150,20); f.add(tbLabel); f.add(b); f.setVisible(true); f.setSize(300,200); } public static void main(String[] args){ EventHandlingExample dd = new EventHandlingExample(); dd.createUI(); } @Override public void actionPerformed(ActionEvent e) { b = (JButton)e.getSource(); sayHi(); } public void sayHi() { JOptionPane.showMessageDialog(f, "Hi, To All.", "Say Hi", JOptionPane.INFORMATION_MESSAGE); } }
Output :
When you will execute the above example you will get the output as follows :
Ads