Google Tag Manager

2009/03/23

aterai

Mouse Dragging ViewPort Scroll

Code

//*
MouseAdapter hsl1 = new HandScrollListener();
vport.addMouseMotionListener(hsl1);
vport.addMouseListener(hsl1);
/*/
MouseAdapter hsl2 = new DragScrollListener();
label.addMouseMotionListener(hsl2);
label.addMouseListener(hsl2);
//*/
class HandScrollListener extends MouseInputAdapter {
  private final Cursor defCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
  private final Cursor hndCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  private final Point pp = new Point();
  @Override
  public void mouseDragged(final MouseEvent e) {
    Point cp = e.getPoint();
    Point vp = vport.getViewPosition();
    //= SwingUtilities.convertPoint(vport,0,0,label);
    vp.translate(pp.x-cp.x, pp.y-cp.y);
    if(r1.isSelected()) {
      label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
    }else{
      vport.setViewPosition(vp);
    }
    pp.setLocation(cp);
  }
  @Override
  public void mousePressed(MouseEvent e) {
    label.setCursor(hndCursor);
    pp.setLocation(e.getPoint());
  }
  @Override
  public void mouseReleased(MouseEvent e) {
    label.setCursor(defCursor);
    label.repaint();
  }
}
class DragScrollListener extends MouseAdapter {
  private final Cursor defCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
  private final Cursor hndCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  private final Point pp = new Point();
  @Override public void mouseDragged(MouseEvent e) {
    final JComponent jc = (JComponent)e.getSource();
    Container c = jc.getParent();
    if(c instanceof JViewport) {
      JViewport vport = (JViewport)c;
      Point cp = SwingUtilities.convertPoint(jc,e.getPoint(),vport);
      Point vp = vport.getViewPosition();
      vp.translate(pp.x-cp.x, pp.y-cp.y);
      jc.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
      pp.setLocation(cp);
    }
  }
  @Override public void mousePressed(MouseEvent e) {
    JComponent jc = (JComponent)e.getSource();
    Container c = jc.getParent();
    if(c instanceof JViewport) {
      jc.setCursor(hndCursor);
      JViewport vport = (JViewport)c;
      Point cp = SwingUtilities.convertPoint(jc,e.getPoint(),vport);
      pp.setLocation(cp);
    }
  }
  @Override public void mouseReleased(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(defCursor);
  }
}

References

3 comments:

  1. Hi,
    your article was very helpful to me. But i am facing a problem when dealing with JTabbedPane. I am unable to drag when i place a JTabbedPane in the Panel. Please help me.

    Thanks
    Anita

    ReplyDelete
  2. Hi Anita,
    This HandScrollListener(DragScrollListener) is not intended for the nested Component.
    So how about using the JLayer: DragScrollLayerTest.java

    ReplyDelete
  3. Hi,
    Thank you very much. You made it very simpler :)

    Thanks,
    Anita

    ReplyDelete