The MouseWheelListener Interface: defines a method to respond to the mouse wheel being rotated : MouseWheelListener « Swing Event « Java Tutorial






Defined MethodDescription
mouseWheelMoved(MouseWheelEvent e)Called when the mouse wheel is rotated


import java.awt.Graphics;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class ZoomingViewer extends JFrame {
  private BufferedImage bi;

  private int zoom = 0;

  private static final double ZOOM_AMOUNT = 1.1;

  public static void main(String[] args) {
      new ZoomingViewer("your.jpg").setVisible(true);
  }

  private void sizeToZoom() {
    double factor = Math.pow(ZOOM_AMOUNT, zoom);
    setSize((int) (bi.getWidth() * factor), (int) (bi.getHeight() * factor));
  }

  public ZoomingViewer(String filename) {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    try {
      bi = ImageIO.read(new File(filename));
    } catch (Exception e) {
      e.printStackTrace();
    }

    sizeToZoom();

    addMouseWheelListener(new MouseWheelListener() {
      public void mouseWheelMoved(MouseWheelEvent e) {
        int steps = e.getWheelRotation();
        zoom += steps;
        sizeToZoom();
      }
    });
  }

  public void paint(Graphics g) {
    g.drawImage(bi, 0, 0, getWidth(), getHeight(), this);
  }
}








15.31.MouseWheelListener
15.31.1.The MouseWheelListener Interface: defines a method to respond to the mouse wheel being rotated
15.31.2.How to Write a Mouse-Wheel ListenerHow to Write a Mouse-Wheel Listener
15.31.3.Handle mouse wheel event