Another approach for handling events is to create separate Listener class for each listener type.
For example : Suppose you want to create a frame window such that when the user clicks in it, the coordinates of the clicked location relative to the left comer of the window are displayed in the console window. For this, you have to create a separate Listener class (say MyMouseListener) that extends the MouseAdapter class and define the mousePressed () method which is triggered and remaining do nothing methods are inherited from the MouseAdapter class.
The complete program is as follows,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyMouseListener extends MouseAdapter
{
public void MousePressed(MouseEvent e)
{
System.out.println("Mouse Pressed at ("+e.getX() +","+ e.getY()+")");
}
}
class SeperateListenerExample extends JFrame
{
SeperateListenerExample()
{
addMouseListener(new MyMouseListener());
}
}
class SeperateListenerJavaExample
{
public static void main(String args[])
{
SeperateListenerExample frame = new SeperateListenerExample();
frame.setTitle("Seperate Listener Java Example");
frame.setBounds(200,150,180,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}
}