package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.MouseWheelEvent;
public class MouseWheelListenerDemo extends JFrame {
public MouseWheelListenerDemo() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MouseWheelListenerDemo().setVisible(true));
}
private void initComponents() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Mouse Wheel Listener Demo");
setSize(500, 500);
JTextArea textArea = new JTextArea();
textArea.addMouseWheelListener(e -> {
System.out.println("MouseWheelListenerDemo.mouseWheelMoved");
// If wheel rotation value is a negative it means rotate up, while
// positive value means rotate down
if (e.getWheelRotation() < 0) {
System.out.println("Rotated Up... " + e.getWheelRotation());
} else {
System.out.println("Rotated Down... " + e.getWheelRotation());
}
// Get scrolled unit amount
System.out.println("ScrollAmount: " + e.getScrollAmount());
// WHEEL_UNIT_SCROLL representing scroll by unit such as the
// arrow keys. WHEEL_BLOCK_SCROLL representing scroll by block
// such as the page-up or page-down key.
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
System.out.println("MouseWheelEvent.WHEEL_UNIT_SCROLL");
}
if (e.getScrollType() == MouseWheelEvent.WHEEL_BLOCK_SCROLL) {
System.out.println("MouseWheelEvent.WHEEL_BLOCK_SCROLL");
}
});
getContentPane().add(textArea);
}
}
The scrolling the mouse wheel the code snippet will print something like:
MouseWheelListenerDemo.mouseWheelMoved
Rotated Down... 1
ScrollAmount: 3
MouseWheelEvent.WHEEL_UNIT_SCROLL
MouseWheelListenerDemo.mouseWheelMoved
Rotated Up... -1
ScrollAmount: 3
MouseWheelEvent.WHEEL_UNIT_SCROLL
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024