Java Event Handling (Part-2)

Discussion in 'Java' started by techgeek.in, Apr 27, 2010.

  1. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
    http://www.techgeek.in
    Parts so far Java Event Handling (Part-1)

    In the previous article I presented the basic concepts and ideas about Event handling in java. In this article I will discuss about mouse event handling.

    Firstly let me familiarize you with the various mouse events.

    MouseEvent Class



    There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them:

    MOUSE_CLICKED -- The user clicked the mouse.
    MOUSE_DRAGGED -- The user dragged the mouse.
    MOUSE_ENTERED -- The mouse entered a component.
    MOUSE_EXITED -- The mouse exited from a component.
    MOUSE_MOVED -- The mouse moved.
    MOUSE_PRESSED -- The mouse was pressed.
    MOUSE_RELEASED -- The mouse was released.
    MOUSE_WHEEL -- The mouse wheel was moved

    MouseEvent is a subclass of InputEvent.

    Here is one of its constructors.

    MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup):- Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.

    int getX(),int getY():-The most commonly used methods in this class are getX() and getY().

    This return the X and Y coordinates of the mouse when the event occurred.

    Point getPoint():- You can also use the getPoint() method to obtain the coordinates of the mouse. It returns a Point object that contains the X, Y coordinates in its integer members: x and y.

    void translatePoint(int x, int y):- The translatePoint()method changes the location of the event.

    Here, the arguments x and y are added to the coordinates of the event.

    int getClickCount():- The getClickCount() method obtains the number of mouse clicks for this event.

    boolean isPopupTrigger():- The isPopupTrigger() method tests if this event causes a pop-up menu to appear on this platform.

    Java 2, version 1.4 adds a second constructor which also allows the button that caused the event to be specified. It added the getButton() method as follows:

    int getButton():- It returns a value that represents the button that caused the event. The return value will be one of these constants defined by MouseEvent.
    • NOBUTTON
    • BUTTON1
    • BUTTON2
    • BUTTON3
    The NOBUTTON value indicates that no button was pressed or released.

    MouseWheelEvent Class



    The MouseWheelEvent class encapsulates a mouse wheel event. It is a subclass of MouseEvent and was added by Java 2, version 1.4. Not all mice have wheels.

    If a mouse has a wheel, it is located between the left and right buttons. Mouse wheels are used for scrolling.

    MouseWheelEvent defines these two integer constants.

    WHEEL_BLOCK_SCROLL -- A page-up or page-down scroll event occurred.
    WHEEL_UNIT_SCROLL -- A line-up or line-down scroll event occurred.

    MouseWheelEvent defines the following constructor.

    MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup, int scrollHow, int amount, int count):- Here, src is a reference to the object that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when the event occurred. The coordinates of the mouse are passed in x and y. The number of clicks the wheel has rotated is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform. The scrollHow value must be either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL. The number of units to scroll is passed in amount. The count parameter indicates the number of rotational units that the wheel moved.

    MouseWheelEvent defines methods that give you access to the wheel event.

    int getWheelRotation():- To obtain the number of rotational units, we can call getWheelRotation().It returns the number of rotational units. If the value is positive, the wheel moved counterclockwise. If the value is negative, the wheel moved clockwise.

    int getScrollType():- To obtain the type of scroll, we can call getScrollType(). It returns either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL. If the scroll type is WHEEL_UNIT_SCROLL

    int getScrollAmount():- we can obtain the number of units to scroll by calling getScrollAmount().

    Now let me discuss about the listener interfaces for mouse events.

    The MouseListener Interface:- This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked() is invoked. When the mouse enters a component, the mouseEntered() method is called. When it leaves, mouseExited() is called. The mousePressed() and mouseReleased() methods are invoked when the mouse is pressed and released, respectively.

    The general forms of these methods are shown here:

    void mouseClicked(MouseEvent me)
    void mouseEntered(MouseEvent me)
    void mouseExited(MouseEvent me)
    void mousePressed(MouseEvent me)
    void mouseReleased(MouseEvent me)


    The MouseMotionListener Interface



    This interface defines two methods. The mouseDragged() method is called multiple times as the mouse is dragged. The mouseMoved() method is called multiple times as the mouse is moved. Their general forms are shown here:

    void mouseDragged(MouseEvent me)
    void mouseMoved(MouseEvent me)


    The MouseWheelListener Interface



    This interface defines the mouseWheelMoved() method that is invoked when the mouse wheel is moved. Its general form is shown here.

    void mouseWheelMoved(MouseWheelEvent mwe)

    Using Handling Mouse Events



    To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces. The following applet demonstrates the process. It displays the current coordinates of the mouse in the applet’s status window. Each time a button is pressed, the word “Down” is displayed at the location of the mouse pointer. Each time the button is released, the word “Up” is shown. If a button is clicked, the mesage “Mouse clicked” is displayed in the upper-left corner of the applet display area.

    As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the applet display area. When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged. Notice that the two variables, mouseX and mouseY, store the location of the mouse when a mouse pressed, released, or dragged event occurs. These coordinates are then used by paint() to display output at the point of these occurrences.

    Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    /*
    <applet code="MouseEvents" width=300 height=100>
    </applet>
    */
    public class MouseEvents extends Applet implements MouseListener, MouseMotionListener 
    {
    	String msg = "";
    	int mouseX = 0, mouseY = 0; // coordinates of mouse
    	public void init() 
    	{
    		addMouseListener(this);
    		addMouseMotionListener(this);
    	}
    	// Handle mouse clicked.
    	public void mouseClicked(MouseEvent me) 
    	{
    		// save coordinates
    		mouseX = 0; 
    		mouseY = 10;
    		msg = "Mouse clicked.";
    		repaint();
    	}
    	// Handle mouse entered.
    	public void mouseEntered(MouseEvent me) 
    	{
    		// save coordinates
    		mouseX = 0;
    		mouseY = 10;
    		msg = "Mouse entered.";
    		repaint();
    	}
    	// Handle mouse exited.
    	public void mouseExited(MouseEvent me) 
    	{
    		// save coordinates
    		mouseX = 0;
    		mouseY = 10;
    		msg = "Mouse exited.";
    		repaint();
    	}
    	// Handle button pressed.
    	public void mousePressed(MouseEvent me) 
    	{
    		// save coordinates
    		mouseX = me.getX();
    		mouseY = me.getY();
    		msg = "Down";
    		repaint();
    	}
    	// Handle button released.
    	public void mouseReleased(MouseEvent me) 
    	{
    		// save coordinates
    		mouseX = me.getX();
    		mouseY = me.getY();
    		msg = "Up";
    		repaint();
    	}
    	// Handle mouse dragged.
    	public void mouseDragged(MouseEvent me) 
    	{
    		// save coordinates
    		mouseX = me.getX();
    		mouseY = me.getY();
    		msg = "*";
    		showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
    		repaint();
    	}
    	// Handle mouse moved.
    	public void mouseMoved(MouseEvent me) 
    	{
    		// show status
    		showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
    	}
    	// Display msg in applet window at current X,Y location.
    	public void paint(Graphics g) 
    	{
    		g.drawString(msg, mouseX, mouseY);
    	}
    }
    
    [​IMG]

    Explanation:- The MouseEvents class extends Applet and implements both the MouseListener and MouseMotionListener interfaces. These two interfaces contain methods that receive and process the various types of mouse events. The applet is both the source and the listener for these events. This works because Component, which supplies the addMouseListener() and addMouseMotionListener() methods, is a superclass of Applet. Being both the source and the listener for events is a common situation for applets. Inside init(), the applet registers itself as a listener for mouse events. This is done by using addMouseListener() and addMouseMotionListener(), which, as mentioned, are members of Component. They are as follows:

    void addMouseListener(MouseListener ml)
    void addMouseMotionListener(MouseMotionListener mml)


    Here, ml is a reference to the object receiving mouse events, and mml is a reference to the object receiving mouse motion events. In this program, the same object is used for both. The applet then implements all of the methods defined by the MouseListener and MouseMotionListener interfaces. These are the event handlers for the various mouse events. Each method handles its event and then returns.

    Adapter Classes



    Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in certain situations. An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested.

    For example, the MouseMotionAdapter class has two methods, mouseDragged() and mouseMoved(). The signatures of these empty methods are exactly as defined in the MouseMotionListener interface. If you were interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged(). The empty implementation of mouseMoved() would handle the mouse motion events for you.

    Following are the commonly used adapter classes in java.awt.event and the interface that each implements.

    ComponentAdapter -- ComponentListener
    ContainerAdapter -- ContainerListener
    FocusAdapter -- FocusListener
    KeyAdapter -- KeyListener
    MouseAdapter -- MouseListener
    MouseMotionAdapter -- MouseMotionListener
    WindowAdapter -- WindowListener

    The following example demonstrates an adapter. It displays a message in the status bar of an applet viewer or browser when the mouse is clicked or dragged. However, all other mouse events are silently ignored. The program has three classes. AdapterDemo extends Applet. Its init() method creates an instance ofMyMouseAdapter and registers that object to receive notifications of mouse events. It also creates an instance of MyMouseMotionAdapter and registers that object to receive notifications of mouse motion events. Both of the constructors take a reference to the applet as an argument. MyMouseAdapter implements the mouseClicked() method. The other mouse events are silently ignored by code inherited from the MouseAdapter class. MyMouseMotionAdapter implements the mouseDragged() method. The other mouse motion event is silently ignored by code inherited from the MouseMotionAdapter class.

    Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    /*
    <applet code="AdapterDemo" width=300 height=100>
    </applet>
    */
    public class AdapterDemo extends Applet 
    {
    	public void init() 
    	{
    		addMouseListener(new MyMouseAdapter(this));
    		addMouseMotionListener(new MyMouseMotionAdapter(this));
    	}
    }
    
    class MyMouseAdapter extends MouseAdapter 
    {
    	AdapterDemo adapterDemo;
    	public MyMouseAdapter(AdapterDemo adapterDemo) 
    	{
    		this.adapterDemo = adapterDemo;
    	}
    	// Handle mouse clicked.
    	public void mouseClicked(MouseEvent me) 
    	{
    		adapterDemo.showStatus("Mouse clicked");
    	}
     }
    class MyMouseMotionAdapter extends MouseMotionAdapter 
    {
    	AdapterDemo adapterDemo;
    	public MyMouseMotionAdapter(AdapterDemo adapterDemo) 
    	{
    		this.adapterDemo = adapterDemo;
    	}
    	// Handle mouse dragged. 
    	public void mouseDragged(MouseEvent me) 
    	{
    		adapterDemo.showStatus("Mouse dragged");
    	}
    }
    
    
    Output:-

    [​IMG]
     
    Last edited by a moderator: Jan 21, 2017
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice