You are here:   HomeJava ProgrammingSwingNamed Inner Class Java Example
by Dinesh Thakur Category: Swing

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);
      }
  }

Java Separate Listener Class Example





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes 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.



What's New and Popular





Popular Article