Mouse Event handling in Java:
The mouse event handling in Java has two methods for interfaces. There are "MouseListeners" and "MouseMotionListeners".These methods are called when the mouse interacts with components.Each of the mouse event-handling methods takes a mouse event object as its arguments. A mouse event object contains information about the mouse event that occurred, including the x- and y-coordinated of the location where the event occurred.
MouseListener interface methods:
public void mousePressed(MouseEvent e)
This method is called when a mouse button is pressed continuously.public void mouseReleased(MouseEvent e)
This method is called when a mouse button is released after being pressed.public void mouseClicked(MouseEvent e)
This method is called when a mouse button is pressed and released. (when the mouse cursor exited from a component).public void mouseEntered(MouseEvent e)
This method is called when a mouse cursor is entered into the component.public void mouseExited(MouseEvent e)
This method is called when a mouse cursor is leaves from a component.MouseMotionListener interface methods:
public void mouseMoved(MouseEvent e)
This method is called when the mouse cursor is moved over the component.public void mouseDragged(MouseEvent e)
This method is called when the mouse button is pressed on a component and moved.Sample program for Mouse-Event Handling:
import java.awt.*;import java.awt.event.*;
import java.applet.*;
/*<applet code="AdaptorDemo" width=300 height=200>
</applet>*/
public class AdaptorDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
addMouseListener(new MyMouseAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
AdaptorDemo adapterdemo;
public MyMouseAdapter(AdaptorDemo adapterdemo)
{
this.adapterdemo=adapterdemo;
}
public void mouseClicked(MouseEvent e)
{
adapterdemo.showStatus("mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter
{
AdaptorDemo adapterdemo;
public MyMouseMotionAdapter(AdaptorDemo adapterdemo)
{
this.adapterdemo=adapterdemo;
}
public void mouseDragged(MouseEvent e)
{
adapterdemo.showStatus("mouse dragged");
}
}
No comments:
Post a Comment