The MouseListener interface defines five methods for handling different operations that are associated with a mouse. These methods are:
- void mouseClicked(MouseEvent me) Is invoked when you click a mouse button.
- void mouseEntered(MouseEvent me) Is invoked when the mouse enters an AWT object to which the mouse event is associated.
- void mouseExited(MouseEvent me) Is invoked when the mouse leaves an AWT object to which the mouse event is associated.
- void mousePressed(MouseEvent me) Is invoked when the mouse key is pressed.
- void mouseReleased(MouseEvent me) Is invoked when the mouse key is released.
The addMouseLister() method is used for monitoring an AWT object for the occurrence of a mouse event. The followning program code shows how to implement the MouseListener interface:
Implementing the MouseListener Interface:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<APPLET Code="MouseListenerTest" Width=300 Height=300>
</APPLET>
*/
public class MouseListenerTest extends Applet implements MouseListener
{
String msg="";
int mx=0, my=0;
public void init()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
mx=me.getX();
my=me.getY();
msg="Mouse Clicked at Position "+mx+" : "+my;
repaint();
}
public void mouseEntered(MouseEvent me)
{
mx=10;
my=10;
msg="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
mx=10;
my=10;
msg="Mouse Left";
repaint();
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void paint(Graphics g)
{
g.drawString(msg,mx,my);
}
}
The above code shows how to implement MouseListener with the Applet window object. The mouseClicked() method display the position where the mouse is clicked in the Applet window. The me.getX() method retrieves the position of the X coordinate where the mouse is clicked. The me.getY() method retrieves the position of the Y coordinate where the mouse is clicked. The mouseEntered() method display a message, Mouse Entered, when the mouse enters the applet window. The mouseExited() method displays a messages, Mouse Exited, when the mouse enters the applet window and code will be stored in the file called MouseListenerTest.java, which on compilation will crate a class file called MouseListenerTest.class. Now compile this file using below commands in the DOS mode:
C:\>jdk1.4\bin>javac MouseListenerTest.java
C:\>jdk1.4\bin>appletviewer MouseListenerTest.java
Event Listener
Action Listener | Adjustment Listener | Mouse Listener |
Mouse Motion Listener | Window Listener | Key Listener |
Focus Listener | ITEM Listener | Text Listener |
Hey, thanks for the blog article.Really looking forward to read more. Cool.
ReplyDeleteSalesforce admin online training
Salesforce admin training
salesforce development online training
salesforce development training
salesforce online training
salesforce training
Advanced Java online training
Advanced Java training