Monday, August 12, 2013

MouseListener and MouseMotionListener

MouseListener interface is used to receive mouse events that are generated by a component when the mouse is pressed, realeased, entered, exited, or clicked. Other mouse events can occur when the mouse is moved or dragged. The later two mouse events are received by the MouseMotionListener interface.

Example:

import java.awt.*;
import java.awt.event.*;
class  Draw extends Frame implements MouseListener,MouseMotionListener{
int x, y;
Draw(String title){

x=y=0;
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
addMouseListener(this);
addMouseMotionListener(this);
setLayout(null);
setTitle(title);
setSize(400,300);
setVisible(true);
requestFocus();
setCursor(new Cursor(Cursor.HAND_CURSOR));

}

public void getMousePos(int x,int y){
this.x=x;
this.y=y;
}


public void mousePressed(MouseEvent e){
getMousePos(e.getX(),e.getY());
}
public void mouseReleased(MouseEvent e){

}
public void mouseEntered(MouseEvent e){

}
public void mouseExited(MouseEvent e){

}
public void mouseClicked(MouseEvent e){

}


public void mouseDragged(MouseEvent e){
int cx=e.getX();
int cy=e.getY();
Graphics g=getGraphics();
g.drawLine(x,y,cx,cy);
getMousePos(cx,cy);
}
public void mouseMoved(MouseEvent e){
}



}
public class SimpleDraw{

public static void main(String args[]){
     new Draw("MouseListener and MouseMotionListener");
 
}


}

MouseListener MouseMotionListener

No comments:

Post a Comment