Tuesday 31 May 2016

How to Add MouseListener to a Frame?

Following example demonstrates basic way of implementing and adding mouse listener interface to frame object.

Step1) Write a class that implements MouseListener interface ( write definitions for mouse listener interface function namely 
1) void mouseClicked(MouseEvent);
2) void mousePressed(MouseEvent);
3) void mouseReleased(MouseEvent);
4) void mouseEntered(MouseEvent);
5) void mouseExited(MouseEvent);

Step2) Create an object of Class
Step3) Write a constructor to create a frame and attach mouse listener obejct to it


/**
*@author Charudatta Ekbote
*/

import java.awt.Frame;
import java.awt.event.*;

class MouseListenerDemo implements MouseListener
{
Frame frame;
MouseListenerDemo() // constructor to instantiate frame object
{
frame = new Frame("MouseListener Demo");
frame.setBounds(100,200,300,400);
frame.setVisible(true);
frame.addMouseListener(this); // here mouse listener object is attached to frame obejct
}

public void mouseClicked(MouseEvent me)  // implementation of mouse clicked event
{
System.out.println("Mouse Clicked");
}

public void mousePressed(MouseEvent me)  // implementation of mouse pressed event
{
System.out.println("Mouse Pressed");
}

public void mouseReleased(MouseEvent me) // implementation of mouse released event
{
System.out.println("Mouse Released");
}

public void mouseEntered(MouseEvent me)  // implementation of mouse entered event
{
System.out.println("Mouse Entered");
}

public void mouseExited(MouseEvent me) // implementation of mouse exited event
{
System.out.println("Mouse Exited");
}

public static void main(String[] arguments) 
{
MouseListenerDemo obejct = new MouseListenerDemo();
}
}

No comments:

Post a Comment