To handle mouse events in Java Applets , you must implement the MouseListener and the MouseMotionListener interfaces. The following applet demonstrates the process. It displays the current coordinates of the mouse in the applet’s status window.
The MouseListener interface defines mouseClicked() , mousePressed() , mouseReleased , mouseExited() and mouseEntered() methods while MouseMotionListener interface defines mouseDragged() and mouseMoved() methods. Here's the java code :
import java.awt.*;
import java.applet.*;
import java.util.*;
import java.awt.event.*;
public class MouseDemo extends Applet implements MouseListener , MouseMotionListener {
String msg="";
int mouseX=0,mouseY=0;
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me){
mouseX=me.getX();
mouseY=me.getY();
msg="Mouse Clicked.";
repaint();
}
public void mouseEntered(MouseEvent me){
mouseX=0;
mouseX=10;
msg="Entered.";
repaint();
}
public void mouseExited(MouseEvent me){
mouseX=0;
mouseX=10;
msg="Exited";
repaint();
}
public void mousePressed(MouseEvent me){
mouseX=0;
mouseY=10;
msg="Down.";
repaint();
}
public void mouseReleased(MouseEvent me){
mouseX=me.getX();
mouseY=me.getY();
msg="up.";
repaint();
}
public void mouseDragged(MouseEvent me){
mouseX=me.getX();
mouseY=me.getY();
msg="*";
showStatus("Dragging mouse at "+mouseX+","+mouseY);
repaint();
}
public void mouseMoved(MouseEvent me){
mouseX=me.getX();
mouseY=me.getY();
showStatus("Mouse is at "+mouseX+","+mouseY);
}
public void paint(Graphics g) {
g.drawString(msg,mouseX,mouseY);
}
}
After building the .class file you can embed this code in an HTML file using the below tag to run the applet in a Web Browser.
<applet source="MouseDemo" width=300 height=100>
</applet>
You can also use an in-built applet viewer ( like the one present in Blue-J ) to demonstrate the created applet .
Hope this helps :)
No comments:
Post a Comment