Monday, 24 November 2014

Handling Mouse Events in Applet using JAVA with Example

Handling Mouse Event in Applet using JAVA with Example

in java there are many events and event handling class and interfaces (ex. MouseEvent, ActionEvent, etc.) for that you have two option to handle it
  1. implementing Interface
  2. extending Adapter class
  • Implementing Interface:- with implementing interface JAVA have many interfaces (ex.MouseLitener, MouseMotionListener, ActionListener etc) with this interfaces you can handle events performed by source control.

    Note: we have consider over here only implementing interface and second one will see in next articl.
  • MouseListenter Interface:this interface is use to handling mouse events like...
public void mouseClicked (MouseEvent me) {}
 public void mouseEntered (MouseEvent me) {}
 public void mousePressed (MouseEvent me) {}
 public void mouseReleased (MouseEvent me) {}
 public void mouseExited (MouseEvent me) {} 
Note: Mouse generates MouseEvent

Handling Mouse Events In Applet Using Java Program

import java.awt.event.*;
import java.awt.*;
import java.applet.*;

/*
<applet code="mouseEvents" height=300 width=300>
</applet>
*/

public class mouseEvents extends Applet implements MouseListener,MouseMotionListener{
    String msg="hello jiten";
    int x,y;
    public void init(){
        x=10;
        y=20;
        addMouseListener(this);
        addMouseMotionListener(this);
    }
    public void paint(Graphics g){
        g.drawString(msg,x,y);
        g.drawLine(10,20,100,120);
    }
    public void mouseClicked(MouseEvent me){
        x=me.getX();
        y=me.getY();
        msg="mouse clicked";
        repaint();
    }
    public void mousePressed(MouseEvent me){
        x=me.getX();
        y=me.getY();
        msg="mouse pressed";
        repaint();
    }
    public void mouseReleased(MouseEvent me){
        x=me.getX();
        y=me.getY();
        msg="mouse released";
        repaint();
    }
    public void mouseDragged(MouseEvent me){
        x=me.getX();
        y=me.getY();
        msg="mouse Dreagged";
        repaint();
    }
    public void mouseMoved(MouseEvent me){
        x=me.getX();
        y=me.getY();
        msg="mouse moved";
        repaint();
    }
    public void mouseEntered(MouseEvent me){
        msg="mouse enterd";
        x=me.getX();
        y=me.getY();
        repaint();
    }
    public void mouseExited(MouseEvent me){
        x=me.getX();
        y=me.getY();
        msg="mouse exited";
        repaint();
    }
}
To run this:
in CMD
for compilation:- javac mouseEvents.java
for Run:- appletviewer mouseEvents.java

No comments:

Post a Comment