Event Listeners:
- Event is an action performed on component.
- When action performed, an object will be created called Event object.
- A listener should collect the event object and handle it.
- java.awt.event providing listener interfaces.
- “Listener” interfaces need to be implemented to defined action logic.
interface ActionListener
{
void actionPerformed(ActionEvent ae);
}
We need to implement above interface and define action logic in actionPerformed method.
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MyFrame extends JFrame
{
static JButton b ;
MyFrame()
{
this.setTitle("First Frame");
this.setSize(400,300);
FlowLayout flow = new FlowLayout();
this.setLayout(flow);
b = new JButton("Click Me");
this.add(b);
b.addActionListener(new ActionLogic());
}
}
class ActionLogic implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("Button clicked...");
}
}
class GUI
{
public static void main(String[] args)
{
MyFrame frame = new MyFrame();
frame.setVisible(true);
}
}
Implementing ActionListener using anonymous inner class:
- In the above application, we write action logic in different class.
- Defining action logics with different classes increase the class files count in application.
- To avoid, we use anonymous inner class.
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MyFrame extends JFrame
{
static JButton b ;
MyFrame()
{
this.setTitle("First Frame");
this.setSize(400,300);
FlowLayout flow = new FlowLayout();
this.setLayout(flow);
b = new JButton("Click Me");
this.add(b);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("Button clicked - anonymous");
}
});
}
}
class GUI
{
public static void main(String[] args)
{
MyFrame frame = new MyFrame();
frame.setVisible(true);
}
}