Wednesday 2 April 2014

MouseListener

The listener interface for receiving mouse events like click, presses, Released, Entered and Exited.


public interface MouseListener extends EventListener {
    public void mouseClicked(MouseEvent e);
    public void mousePressed(MouseEvent e);
    public void mouseReleased(MouseEvent e);
    public void mouseEntered(MouseEvent e);
    public void mouseExited(MouseEvent e);
}

void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed and released) on a component.

void mousePressed(MouseEvent e)
Invoked when a mouse button has been pressed on a component.

void mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.

void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.

void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.*;

public class MouseListenerEx{
 JTextArea displayArea;
 JTextField typingArea;
 JFrame frame1;
  
 MouseListenerEx(){
  
  /* Initialize typingArea */
  typingArea = new JTextField(20);
  
  /* Initialize Display Area */
  displayArea = new JTextArea();
  displayArea.setEditable(false);
  JScrollPane scrollPane = new JScrollPane(displayArea);
  scrollPane.setPreferredSize(new Dimension(375, 125));
   
  /* Initialize Frame */
  frame1 =new JFrame("Sample Frame");
  frame1.pack();
  frame1.setVisible(true);
  frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame1.getContentPane().add(typingArea, BorderLayout.PAGE_START);
  frame1.getContentPane().add(scrollPane, BorderLayout.CENTER);
  frame1.setSize(300, 500);
    
  /* Add Key Listener */
  typingArea.addMouseListener(new MouseListener(){
   public void mouseClicked(MouseEvent e){
    displayArea.append("Mouse Clicked\n" + e +"\n");
   }
    
   public void mousePressed(MouseEvent e){
    displayArea.append("Mouse Pressed\n " + e +"\n");
   }
    
   public void mouseReleased(MouseEvent e){
    displayArea.append("Mouse Released\n" + e +"\n");
   }
   
   public void mouseEntered(MouseEvent e){
    displayArea.append("Mouse Entered\n" + e +"\n");
   }
   
   public void mouseExited(MouseEvent e){
    displayArea.append("Mouse Exited\n" + e +"\n");
   }
  });   
 }
 
 public static void main(String args[]){
  new MouseListenerEx();
 }
}

Output






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment