Using MouseWheelListener on AWT Frame

The following illustrates using MouseWheelListener on AWT Frame. MouseWheelEvent is generated when a mouse wheel is moved.
import java.awt.*;
import java.awt.event.*;
class FrameMouseWheelListener extends Frame implements MouseWheelListener
{
Label l;

    public FrameMouseWheelListener()
    {
        createAndShowGUI();
    }
    
    private void createAndShowGUI()
    {
        setTitle("MouseWheelEvent for Frame Demo");
        setLayout(new FlowLayout());
        
        l=new Label("I go up and down");
        add(l);
        
        // Add MouseWheelListener to this frame
        addMouseWheelListener(this);
        
        setSize(400,400);
        setVisible(true);
    }

    public void mouseWheelMoved(MouseWheelEvent me)
    {
    // Get current co-ordinates
    int x=l.getX();
    int y=l.getY();
    
    // Get the amount to scroll
    int amt=me.getScrollAmount();
    
        // -1 = upward; 1 = downward
        if(me.getWheelRotation()==-1)
        l.setLocation(x,y-amt);
        else
        l.setLocation(x,y+amt);
    }
    
    public static void main(String args[])
    {
        new FrameMouseWheelListener();
    }
}

When the mouse wheel is pushed to the opposite side then the label is moved upwards so is y-amt where y is the current y co-ordinate. Here, x co-ordinate is kept constant. Note that MouseWheelListener is added to the Frame and not to the Label but the effect is on Label.

FrameMouseWheelListener(): This invokes code illustrating the MouseWheelEvent on AWT Frame.

Using MouseWheelListener on AWT Frame

Next: Using WindowListener for AWT Frame
 Previous: Using MouseMotionListener on AWT Frame

No comments: