We can use inner class to handle events.
// Demonstrate the key event handlers. import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; class SimpleKey extends JTextArea { public SimpleKey() { addMouseListener(new MyMouseAdapter(this)); addMouseMotionListener(new MyMouseMotionAdapter(this)); }/*from w ww. j ava2 s. c o m*/ class MyMouseAdapter extends MouseAdapter { SimpleKey adapterDemo; public MyMouseAdapter(SimpleKey adapterDemo) { this.adapterDemo = adapterDemo; } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { adapterDemo.append("Mouse clicked"); } } class MyMouseMotionAdapter extends MouseMotionAdapter { SimpleKey adapterDemo; public MyMouseMotionAdapter(SimpleKey adapterDemo) { this.adapterDemo = adapterDemo; } // Handle mouse dragged. public void mouseDragged(MouseEvent me) { adapterDemo.append("Mouse dragged"); } } } public class Main { public static void main(String args[]) { // Create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { // Create a new JFrame container. JFrame jfrm = new JFrame("java2s.com"); // Give the frame an initial size. jfrm.setSize(220, 200); // Terminate the program when the user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Add the label to the content pane. jfrm.add(new JScrollPane(new SimpleKey())); // Display the frame. jfrm.setVisible(true); } }); } }