ADS

Using Mouselistener For Awt Frame

The following illustrates using MouseListener for AWT Frame. MouseListener listens to MouseEvent such as mousePressed, mouseReleased, mouseClicked, mouseEntered, mouseExited.
 import java.awt.*;
import java.awt.event.*;
class FrameMouseEvent extends Frame implements MouseListener
{
    public FrameMouseEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("MouseEvent for Frame Demo");
        setSize(400,400);
        setVisible(true);
       
        // Add MouseListener to this frame
        addMouseListener(this);
    }
   
    public void mouseEntered(MouseEvent me)
    {
        setBackground(Color.GRAY);
    }
   
    public void mouseExited(MouseEvent me)
    {
        setBackground(Color.WHITE);
    }
   
    public void mousePressed(MouseEvent me)
    {
        setBackground(Color.DARK_GRAY);
    }
   
    public void mouseReleased(MouseEvent me)
    {
        setBackground(Color.LIGHT_GRAY);
    }
   
    public void mouseClicked(MouseEvent me)
    {
        setBackground(Color.BLACK);
    }
   
    public static void main(String args[])
    {
        new FrameMouseEvent();
    }
}

To see the effect of mouseReleased(), try pressing the mouse at a point and releasing it at another point.
mouseClicked() means pressing and releasing a mouse button at the same point. mouseEntered() and mouseExited() are executed when the cursor enters and exits the frame respectively.

FrameMouseEvent(): This contains code that illustrates use of MouseListener with AWT Frame.
new FrameMouseEvent(): Creates an object for the FrameMouseEvent class.

 MouseListener listens to MouseEvent such as mousePressed Using MouseListener for AWT Frame

Next: Using MouseMotionListener on AWT Frame
Previous: Using TextListener for AWT TextField

Subscribe to receive free email updates:

ADS