Mouse Motion Listener Application

<< Mouse Listener Application | Applications | Dueling Robots Example >>

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class MouseMotionApplication extends JPanel implements MouseMotionListener
{
	public static int WIDTH=800;
	public static int HEIGHT=600;
    private Font titleFont, regularFont;
    private int x,y;


    public MouseMotionApplication()
    {

    	//initialize variables here...
    	titleFont = new Font("Roman", Font.BOLD, 18);
    	regularFont = new Font("Helvetica", Font.PLAIN, 12);
    	x=0;
    	y=0;

    }
	public static void main(String[] args) {
		MouseMotionApplication app= new MouseMotionApplication();
		JFrame window = new JFrame("Mouse Motion Listener Application");
		window.setSize(WIDTH, HEIGHT);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().add(app);

		window.getContentPane().addMouseMotionListener(app);

		window.setVisible(true);

	}
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, getWidth(),getHeight());
		g.setColor(Color.MAGENTA);
		g.setFont(titleFont);
		g.drawString("MouseMotionListener Application", 20, 20);
		g.drawString("X = "+x+"   Y = "+y, 20, 100);
		g.setColor(Color.BLACK);
		g.setFont(regularFont);
		g.drawString("Move your mouse", 20, 40);
		g.setColor(Color.BLUE);
		g.fillOval(x-15, y-40, 30, 30);

	}
	// update is a workaround to cure Windows screen flicker problem
	public void update(Graphics g){
		paint(g);
	}
	/**
	 * These are the Methods needed to implement the MouseMotionListener Interface
	 */

	@Override
	public void mouseDragged(MouseEvent e) {


	}
	@Override
	public void mouseMoved(MouseEvent e) {
		x=e.getX();
		y=e.getY();
		repaint();
	}



}