event

MouseWheelListener example

With this tutorial we are going to show you how to use a MouseWheelListener in Java. This event listener is particularly useful when you want to add extra user friendly functionality in your application. For example, if you want the user to change the value of a specific item, you can allow him to do that using the wheel of the mouse.

In short in order to work with MouseWheelListener in Java you can:

  • Create a new MouseWheelListener
  • Override the mouseWheelMoved method, which will fire up every time the user moves the mouse wheel.
  • Use addMouseWheelListener method to bundle a specific component with the listener. Every time the cursor is in the area of the component and the wheel is moved the listener will handle the event as we said before.

Let’s see the code snippets that follow:

package com.javacodegeeks.snippets.desktop;

import java.awt.Color;
import java.awt.Container;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JFrame;

public class MouseWheelListenerExample extends JFrame {

    private static final Color colorArray[] = {Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN,

  Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW};

    public MouseWheelListenerExample() {

  super();

  final Container cPane = getContentPane();

  MouseWheelListener mouseWheelListener = new MouseWheelListener() {

int cnt;

private static final int up_color = 1;

private static final int down_col = 2;

@Override

public void mouseWheelMoved(MouseWheelEvent event) {

    int stps = event.getWheelRotation();

    int dir = (Math.abs(stps) > 0) ? up_color : down_col;

    changeBackground(dir);

}

private void changeBackground(int dir) {

    cPane.setBackground(colorArray[cnt]);

    if (dir == up_color) {

  cnt++;

    } else {

  --cnt;

    }

    if (cnt == colorArray.length) {

  cnt = 0;

    } else if (cnt < 0) {

  cnt = colorArray.length - 1;

    }

}

  };

  cPane.addMouseWheelListener(mouseWheelListener);
    }

    public static void main(String args[]) {

  JFrame jFrame = new MouseWheelListenerExample();

  jFrame.setSize(600, 400);

  jFrame.setVisible(true);
    }
}

This was an example no how to use MouseWheelListener in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
skymab
skymab
6 years ago

did you even test your code?

int dir = (Math.abs(stps) > 0) ? up_color : down_col;

Do you notice something? Something which has to do with Math.abs?

Back to top button