Friday, July 19, 2024

Simple MouseMotionListener in Java Swing

 // Simple MouseMotionListener in Java Swing

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;


public class mouseMotionListener extends JFrame implements MouseMotionListener

{

JFrame f;


public mouseMotionListener()

{

f=new JFrame("Simple MouseMotionListener Example");


f.addMouseMotionListener(this);


f.setLocationRelativeTo(null);

f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);

f.setSize(500,300);

f.setVisible(true);

}

public void mouseDragged(MouseEvent me)

{

f.getContentPane().setBackground(Color.BLUE);

}

public void mouseMoved(MouseEvent me)

{

f.getContentPane().setBackground(Color.YELLOW);

}

public static void main(String args[])

{

new mouseMotionListener();

}

}


Output :-


                  Whenever mouseDragged() Event Fired Color Will Become Blue.
                     Whenever mouseMoved() Event Fired Color Will Become Yellow.