Written by Sai Sandeep Thota on November 30, 2013 in Java > Programming

Java Program to Capture Mouse Actions in Applets

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Mouse actions can be captured in Applets. For example: if you would like to track what an user is doing like if he has pressed the mouse, clicked, dragged etc., We can implement them using MouseListener and MouseMotionListener interface.

The methods we are defining here are mouseEntered, mouseExited, mouseClicked, mousePressed, mouseDragged, mouseReleased, mouseMoved and they are associated with MouseEvent object. They are invoked when the action is triggered.

In init() method we are attaching MouseMotionListener and MouseListener. So what does this program exactly do? For instance: If you click your mouse, the method associated with the Mouse click event is triggered and action is printed to the screen.

repaint() method is used update the screen by calling paint() method.

Java Program to Capture Mouse Actions in Applets

/*
More at ProgrammingUnit.com
*/
import java.awt.event.*;
import java.applet.*;
import java.awt.*;

/*
<applet code="displayMouseActions" width="400" height="400">
</applet>
*/

public class displayMouseActions extends Applet implements MouseListener, MouseMotionListener
{
	String msg="";
	public void init()
	{
		addMouseListener(this);
		addMouseMotionListener(this);
		setBackground(Color.yellow);
	}

	public void mouseEntered(MouseEvent me)
	{
		msg="Mouse Entered";
		repaint();
	}

	public void mouseExited(MouseEvent me)
	{
		msg="Mouse Exited";
		repaint();
	}

	public void mouseClicked(MouseEvent me)
	{
		msg="Mouse Clicked";
		repaint();
	}

	public void mousePressed(MouseEvent me)
	{
		msg="Mouse Pressed";
		repaint();
	}

	public void mouseReleased(MouseEvent me)
	{
		msg="Mouse Released";
		repaint();
	}

	public void mouseDragged(MouseEvent me)
	{
		msg="Mouse Dragged";
		repaint();
	}

	public void mouseMoved(MouseEvent me)
	{
		msg="Mouse Moved";	
		repaint();
	}

	public void paint(Graphics g)
	{
		g.drawString(msg, 0, 20);
	}
}

Download Source Code

Output
mouse_actions

Video

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: