Java Swing How to - Autoscroll a JScrollpane when dragging an object








Question

We would like to know how to autoscroll a JScrollpane when dragging an object.

Answer

import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.net.URL;
/* w  w  w  .ja v  a 2s.  c  om*/
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Main {
  public static void main(String[] args) throws Exception {
    JFrame f = new JFrame(Main.class.getSimpleName());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    BufferedImage bi = ImageIO.read(new URL(
        "http://www.java2s.com/style/download.png"));
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel(new ImageIcon(bi));
    panel.add(label);
    MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
      @Override
      public void mouseDragged(MouseEvent e) {
        Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
        ((JPanel) e.getSource()).scrollRectToVisible(r);
      }
    };
    panel.addMouseMotionListener(doScrollRectToVisible);

    panel.setAutoscrolls(true);
    f.add(new JScrollPane(panel));
    f.pack();
    f.setSize(f.getWidth() / 2, f.getHeight() / 2);
    f.setVisible(true);
  }
}