Google Tag Manager

2008/06/25

Mouse Drag Auto Scrolling

Code

class ViewportDragScrollListener extends MouseAdapter
                                 implements HierarchyListener {
  private static final int SPEED = 4;
  private static final int DELAY = 10;
  private final Cursor dc;
  private final Cursor hc = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  private final Timer scroller;
  private final JComponent label;
  private Point startPt = new Point();
  private Point move    = new Point();

  public ViewportDragScrollListener(JComponent comp) {
    this.label = comp;
    this.dc = comp.getCursor();
    this.scroller = new Timer(DELAY, new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        Container c = SwingUtilities.getAncestorOfClass(
            JViewport.class, label);
        if (c instanceof JViewport.class) {
          JViewport vport = (JViewport) c;
          Rectangle rect = vport.getViewRect();
          rect.translate(move.x, move.y);
          label.scrollRectToVisible(rect);
        }
      }
    });
  }

  @Override public void hierarchyChanged(HierarchyEvent e) {
    JComponent c = (JComponent) e.getSource();
    if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0
        && !c.isDisplayable()) {
      scroller.stop();
    }
  }

  @Override public void mouseDragged(MouseEvent e) {
    JViewport vport = (JViewport) e.getSource();
    Point pt = e.getPoint();
    int dx = startPt.x - pt.x;
    int dy = startPt.y - pt.y;
    Rectangle rect = vport.getViewRect();
    rect.translate(dx, dy);
    label.scrollRectToVisible(rect);
    move.setLocation(SPEED * dx, SPEED * dy);
    startPt.setLocation(pt);
  }

  @Override public void mousePressed(MouseEvent e) {
    e.getComponent().setCursor(hc); // label.setCursor(hc);
    startPt.setLocation(e.getPoint());
    move.setLocation(0, 0);
    scroller.stop();
  }

  @Override public void mouseReleased(MouseEvent e) {
    e.getComponent().setCursor(dc); // label.setCursor(dc);
    scroller.start();
  }

  @Override public void mouseExited(MouseEvent e) {
    e.getComponent().setCursor(dc); // label.setCursor(dc);
    move.setLocation(0, 0);
    scroller.stop();
  }
}

References

6 comments:

  1. Thanks a lot! I've looked for quite some time for an example on how to do something like this!

    Your DragMoverListener class was exactly what I needed!

    Regards, Jacob

    ReplyDelete
  2. its been a long time aterai, but do you have msn? i would like to contact you about something i want to make and want to incorporate what you have made here. could i contact you over msn if you have it?

    ReplyDelete
  3. Sorry for the late reply.
    I don't have MSN Messenger.
    My native language is not english, I am terrible at chatting.
    You can reach me by E-mail at: at.terai@gmail.com

    ReplyDelete
  4. I just want to say, Thanks a lot!!!!

    ReplyDelete