Google Tag Manager

Showing posts with label MouseMotionListener. Show all posts
Showing posts with label MouseMotionListener. Show all posts

2019/02/27

aterai

Limit the movable range of JSlider's value

Code

public static final int MAXI = 80;
public static final int MINI = 40;

private static class MetalDragLimitedSliderUI extends MetalSliderUI {
  @Override protected TrackListener createTrackListener(JSlider slider) {
    return new TrackListener() {
      @Override public void mouseDragged(MouseEvent e) {
        // case HORIZONTAL:
        int halfThumbWidth = thumbRect.width / 2;
        int thumbLeft = e.getX() - offset;
        int maxPos = xPositionForValue(MAXI) - halfThumbWidth;
        int minPos = xPositionForValue(MINI) - halfThumbWidth;
        if (thumbLeft > maxPos) {
          e.translatePoint(maxPos + offset - e.getX(), 0);
        } else if (thumbLeft < minPos) {
          e.translatePoint(minPos + offset - e.getX(), 0);
        }
        super.mouseDragged(e);
      }
    };
  }
}

private static JSlider makeSilder(String title) {
  JSlider slider = new JSlider(0, 100, 40);
  slider.setBorder(BorderFactory.createTitledBorder(title));
  slider.setMajorTickSpacing(10);
  slider.setPaintTicks(true);
  slider.setPaintLabels(true);
  Dictionary<?, ?> dictionary = slider.getLabelTable();
  if (Objects.nonNull(dictionary)) {
    Enumeration<?> elements = dictionary.elements();
    while (elements.hasMoreElements()) {
      JLabel label = (JLabel) elements.nextElement();
      int v = Integer.parseInt(label.getText());
      if (v > MAXI || v < MINI) {
        label.setForeground(Color.RED);
      }
    }
  }
  slider.getModel().addChangeListener(e -> {
    BoundedRangeModel m = (BoundedRangeModel) e.getSource();
    if (m.getValue() > MAXI) {
      m.setValue(MAXI);
    } else if (m.getValue() < MINI) {
      m.setValue(MINI);
    }
  });
  return slider;
}

References

2014/12/31

aterai

Draggable and sortable JPanels

Code

class RearrangingHandler extends MouseAdapter {
  private static final int xoffset = 16;
  private static final Rectangle R1 = new Rectangle();
  private static final Rectangle R2 = new Rectangle();
  private static Rectangle prevRect;
  private final int gestureMotionThreshold = DragSource.getDragThreshold();
  private final JWindow window = new JWindow();
  private int index = -1;
  private Component draggingComonent;
  private Component gap;
  private Point startPt;
  private Point dragOffset;

  public RearrangingHandler() {
    super();
    window.setBackground(new Color(0, true));
  }
  @Override public void mousePressed(MouseEvent e) {
    if (((JComponent) e.getComponent()).getComponentCount() <= 1) {
      startPt = null;
    } else {
      startPt = e.getPoint();
    }
  }
  private void startDragging(JComponent parent, Point pt) {
    Component c = parent.getComponentAt(pt);
    index = parent.getComponentZOrder(c);
    if (Objects.equals(c, parent) || index < 0) {
      return;
    }
    draggingComonent = c;
    Dimension d = draggingComonent.getSize();

    Point dp = draggingComonent.getLocation();
    dragOffset = new Point(pt.x - dp.x, pt.y - dp.y);

    gap = Box.createRigidArea(d);
    swapComponentLocation(parent, c, gap, index);

    window.add(draggingComonent);
    //window.setSize(d);
    window.pack();

    updateWindowLocation(pt, parent);
    window.setVisible(true);
  }
  private void updateWindowLocation(Point pt, JComponent parent) {
    Point p = new Point(pt.x - dragOffset.x, pt.y - dragOffset.y);
    SwingUtilities.convertPointToScreen(p, parent);
    window.setLocation(p);
  }
  private static int getTargetIndex(Rectangle r, Point pt, int i) {
    int ht2 = (int)(.5 + r.height * .5);
    R1.setBounds(r.x, r.y,       r.width, ht2);
    R2.setBounds(r.x, r.y + ht2, r.width, ht2);
    if (R1.contains(pt)) {
      prevRect = R1;
      return i - 1 > 0 ? i : 0;
    } else if (R2.contains(pt)) {
      prevRect = R2;
      return i;
    }
    return -1;
  }
  private static void swapComponentLocation(
      Container parent, Component remove, Component add, int idx) {
    parent.remove(remove);
    parent.add(add, idx);
    parent.revalidate();
    parent.repaint();
  }
  @Override public void mouseDragged(MouseEvent e) {
    Point pt = e.getPoint();
    JComponent parent = (JComponent) e.getComponent();
    double a = Math.pow(pt.x - startPt.x, 2);
    double b = Math.pow(pt.y - startPt.y, 2);
    if (draggingComonent == null &&
        Math.sqrt(a + b) > gestureMotionThreshold) {
      startDragging(parent, pt);
      return;
    }
    if (!window.isVisible() || draggingComonent == null) {
      return;
    }
    updateWindowLocation(pt, parent);
    if (prevRect != null && prevRect.contains(pt)) {
      return;
    }

    for (int i = 0; i < parent.getComponentCount(); i++) {
      Component c = parent.getComponent(i);
      Rectangle r = c.getBounds();
      if (Objects.equals(c, gap) && r.contains(pt)) {
        return;
      }
      int tgt = getTargetIndex(r, pt, i);
      if (tgt >= 0) {
        swapComponentLocation(parent, gap, gap, tgt);
        return;
      }
    }
    //System.out.println("outer");
    parent.remove(gap);
    parent.revalidate();
  }

  @Override public void mouseReleased(MouseEvent e) {
    startPt = null;
    if (!window.isVisible() || draggingComonent == null) {
      return;
    }
    Point pt = e.getPoint();
    JComponent parent = (JComponent) e.getComponent();

    Component cmp = draggingComonent;
    draggingComonent = null;
    prevRect = null;
    startPt = null;
    dragOffset = null;
    window.setVisible(false);

    for (int i = 0; i < parent.getComponentCount(); i++) {
      Component c = parent.getComponent(i);
      if (Objects.equals(c, gap)) {
        swapComponentLocation(parent, gap, cmp, i);
        return;
      }
      int tgt = getTargetIndex(c.getBounds(), pt, i);
      if (tgt >= 0) {
        swapComponentLocation(parent, gap, cmp, tgt);
        return;
      }
    }
    if (parent.getParent().getBounds().contains(pt)) {
      swapComponentLocation(parent, gap, cmp, parent.getComponentCount());
    } else {
      swapComponentLocation(parent, gap, cmp, index);
    }
  }
}

References

2013/04/25

aterai

Rearrange JToolBar icon by drag and drop

Code

class DragHandler extends MouseAdapter{
  private final JWindow window = new JWindow();
  private Component draggingComonent = null;
  private int index = -1;
  private Component gap = Box.createHorizontalStrut(24);
  private Point startPt = null;
  private int gestureMotionThreshold = DragSource.getDragThreshold();
  public DragHandler() {
    window.setBackground(new Color(0, true));
  }
  @Override public void mousePressed(MouseEvent e) {
    JComponent parent = (JComponent)e.getComponent();
    if(parent.getComponentCount()<=1) {
      startPt = null;
      return;
    }
    startPt = e.getPoint();
  }
  @Override
  public void mouseDragged(MouseEvent e) {
    Point pt = e.getPoint();
    JComponent parent = (JComponent)e.getComponent();
    int t = Math.sqrt(Math.pow(pt.x-startPt.x, 2)+Math.pow(pt.y-startPt.y, 2))
    if(startPt != null && t>gestureMotionThreshold) {
      startPt = null;
      Component c = parent.getComponentAt(pt);
      index = parent.getComponentZOrder(c);
      if(c == parent || index < 0) {
        return;
      }
      draggingComonent = c;

      parent.remove(draggingComonent);
      parent.add(gap, index);
      parent.revalidate();
      parent.repaint();

      window.add(draggingComonent);
      window.pack();

      Dimension d = draggingComonent.getPreferredSize();
      Point p = new Point(pt.x - d.width/2, pt.y - d.height/2);
      SwingUtilities.convertPointToScreen(p, parent);
      window.setLocation(p);
      window.setVisible(true);

      return;
    }
    if(!window.isVisible() || draggingComonent==null) {
      return;
    }

    Dimension d = draggingComonent.getPreferredSize();
    Point p = new Point(pt.x - d.width/2, pt.y - d.height/2);
    SwingUtilities.convertPointToScreen(p, parent);
    window.setLocation(p);

    for(int i=0; i=0 ? i : 0;
        parent.remove(gap);
        parent.add(gap, n);
        parent.revalidate();
        parent.repaint();
        return;
      }else if(r2.contains(pt)) {
        if(c==gap) {
          return;
        }
        parent.remove(gap);
        parent.add(gap, i);
        parent.revalidate();
        parent.repaint();
        return;
      }
    }
    parent.remove(gap);
    parent.revalidate();
    parent.repaint();
  }

  @Override
  public void mouseReleased(MouseEvent e) {
    startPt = null;
    if(!window.isVisible() || draggingComonent==null) {
      return;
    }
    Point pt = e.getPoint();
    JComponent parent = (JComponent)e.getComponent();

    Component cmp = draggingComonent;
    draggingComonent = null;
    window.setVisible(false);

    for(int i=0; i=0 ? i : 0;
        parent.remove(gap);
        parent.add(cmp, n);
        parent.revalidate();
        parent.repaint();
        return;
      }else if(r2.contains(pt)) {
        parent.remove(gap);
        parent.add(cmp, i);
        parent.revalidate();
        parent.repaint();
        return;
      }
    }
    if(parent.getBounds().contains(pt)) {
      parent.remove(gap);
      parent.add(cmp);
    }else{
      parent.remove(gap);
      parent.add(cmp, index);
    }
    parent.revalidate();
    parent.repaint();
  }
}

References

2010/05/10

aterai

Custom Decorated TitleBar JFrame

Code

class ResizeWindowListener extends MouseAdapter {
  private Rectangle startSide = null;
  private final JFrame frame;
  public ResizeWindowListener(JFrame frame) {
    this.frame = frame;
  }
  public void mousePressed(MouseEvent e) {
    startSide = frame.getBounds();
  }
  public void mouseDragged(MouseEvent e) {
    if(startSide==null) return;
    Component c = e.getComponent();
    if(c==topleft) {
      startSide.y += e.getY();
      startSide.height -= e.getY();
      startSide.x += e.getX();
      startSide.width -= e.getX();
    }else if(c==top) {
      startSide.y += e.getY();
      startSide.height -= e.getY();
    }else if(c==topright) {
      startSide.y += e.getY();
      startSide.height -= e.getY();
      startSide.width += e.getX();
    }else if(c==left) {
      startSide.x += e.getX();
      startSide.width -= e.getX();
    }else if(c==right) {
      startSide.width += e.getX();
    }else if(c==bottomleft) {
      startSide.height += e.getY();
      startSide.x += e.getX();
      startSide.width -= e.getX();
    }else if(c==bottom) {
      startSide.height += e.getY();
    }else if(c==bottomright) {
      startSide.height += e.getY();
      startSide.width += e.getX();
    }
    frame.setBounds(startSide);
  }
}

References

2009/12/21

aterai

snap to ticks drag JSlider

Code

slider.setUI(new MetalSliderUI() {
  protected TrackListener createTrackListener(final JSlider slider) {
    return new TrackListener() {
      public void mouseDragged(MouseEvent e) {
        if(!slider.getSnapToTicks() || slider.getMajorTickSpacing()==0) {
          super.mouseDragged(e);
          return;
        }
        //case JSlider.HORIZONTAL:
        int halfThumbWidth    = thumbRect.width / 2;
        int trackLength = trackRect.width;
        int trackLeft  = trackRect.x-halfThumbWidth;
        int trackRight = trackRect.x+(trackRect.width-1)+halfThumbWidth;
        int xPos = e.getX();
        int snappedPos = xPos;
        if (xPos < = trackLeft) {
          snappedPos = trackLeft;
        } else if (xPos > = trackRight) {
          snappedPos = trackRight;
        } else {
          //int tickSpacing = slider.getMajorTickSpacing();
          //float actualPixelsForOneTick = trackLength * tickSpacing
          //                                 / (float)slider.getMaximum();
          // a problem if you choose to set a negative MINIMUM for
          // the JSlider; the calculated drag-positions are wrong.
          // Fixed by bobndrew:
          int possibleTickPositions=slider.getMaximum()-slider.getMinimum();
          int tickSpacing = (slider.getMinorTickSpacing()==0)
                            ? slider.getMajorTickSpacing()
                            : slider.getMinorTickSpacing();
          float actualPixelsForOneTick = trackLength * tickSpacing
                                         / (float)possibleTickPositions;
          xPos -= trackLeft;
          snappedPos=(int)(
            (Math.round(xPos/actualPixelsForOneTick)*actualPixelsForOneTick)+0.5)
            +trackLeft;
          offset = 0;
        }
        MouseEvent me = new MouseEvent(
          e.getComponent(), e.getID(), e.getWhen(), e.getModifiers(),
          snappedPos, e.getY(),
          e.getXOnScreen(), e.getYOnScreen(),
          e.getClickCount(), e.isPopupTrigger(), e.getButton());
        super.mouseDragged(me);
      }
    };
  }
});

References

2009/11/30

aterai

Jump to clicked position JSlider

Code

slider.setUI(new MetalSliderUI() {
  @Override protected TrackListener createTrackListener(JSlider slider) {
    return new TrackListener() {
      @Override public void mousePressed(MouseEvent e) {
        if (UIManager.getBoolean("Slider.onlyLeftMouseButtonDrag")
              && SwingUtilities.isLeftMouseButton(e)) {
          JSlider slider = (JSlider) e.getComponent();
          switch (slider.getOrientation()) {
          case SwingConstants.VERTICAL:
            slider.setValue(valueForYPosition(e.getY()));
            break;
          case SwingConstants.HORIZONTAL:
            slider.setValue(valueForXPosition(e.getX()));
            break;
          default:
            throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL");
          }
          super.mousePressed(e); //isDragging = true;
          super.mouseDragged(e);
        } else {
          super.mousePressed(e);
        }
      }
      @Override public boolean shouldScroll(int direction) {
        return false;
      }
    };
  }
});

References

2009/11/13

aterai

add JInternalFrame to Undecorated JFrame

Code

//JFrame without close, minimize, maximize buttons.
final JInternalFrame internal = new JInternalFrame();
BasicInternalFrameUI ui = (BasicInternalFrameUI)internal.getUI();
Component title = ui.getNorthPane();
for(MouseMotionListener l:title.getListeners(MouseMotionListener.class)) {
  title.removeMouseMotionListener(l);
}
DragWindowListener dwl = new DragWindowListener();
title.addMouseListener(dwl);
title.addMouseMotionListener(dwl);
JPanel p = new JPanel(new BorderLayout());
p.add(new JScrollPane(new JTree()));
p.add(new JButton(new AbstractAction("close") {
  public void actionPerformed(ActionEvent e) {
    Window w = SwingUtilities.windowForComponent((Component)e.getSource());
    w.getToolkit().getSystemEventQueue().postEvent(
      new WindowEvent(w, WindowEvent.WINDOW_CLOSING));
  }
}), BorderLayout.SOUTH);
internal.getContentPane().add(p);
internal.setVisible(true);
KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
focusManager.addPropertyChangeListener(new PropertyChangeListener() {
  public void propertyChange(PropertyChangeEvent e) {
    String prop = e.getPropertyName();
    if("activeWindow".equals(prop)) {
      try{
        internal.setSelected(e.getNewValue()!=null);
      }catch(PropertyVetoException ex) {
        ex.printStackTrace();
      }
    }
  }

References

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

2008/12/25

aterai

JTable FishEye Row

Code

public void mouseMoved(MouseEvent e) {
  int row = rowAtPoint(e.getPoint());
  if(prev_row==row) return;
  initRowHeigth(prev_height, row);
  prev_row = row;
}
public void initRowHeigth(int height, int ccRow) {
  int rd2      = (fishEyeRowList.size()-1)/2;
  int rowCount = getModel().getRowCount();
  int view_rc  = getViewableColoredRowCount(ccRow);
  int view_h   = 0; for(int i=0;i < view_rc;i++) view_h += fishEyeRowHeightList.get(i);
  int rest_rc  = rowCount - view_rc;
  int rest_h   = height - view_h;
  int rest_rh  = rest_h/rest_rc; rest_rh = rest_rh > 0?rest_rh:1;
  int a        = rest_h - rest_rh*rest_rc;
  int index    = -1;
  for(int i=-rd2;i < rowCount;i++) {
    int crh;
    if(ccRow-rd2 <= i && i <= ccRow+rd2) {
      index++;
      if(i < 0) continue;
      crh = fishEyeRowHeightList.get(index);
    }else{
      if(i < 0) continue;
      crh = rest_rh+(a > 0?1:0);
      a = a-1;
    }
    setRowHeight(i, crh);
  }
}

References

2008/10/14

aterai

rubber band selection, drag and drop reordering

Code

JList list = new JList(model);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(0);
list.setFixedCellWidth(62);
list.setFixedCellHeight(62);
list.setCellRenderer(new IconListCellRenderer());
RubberBandingListener rbl = new RubberBandingListener();
list.addMouseMotionListener(rbl);
list.addMouseListener(rbl);
list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setTransferHandler(new ListItemTransferHandler());
list.setDropMode(DropMode.INSERT);

References

2008/10/09

aterai

using rubber band selection in JList

Code

class RubberBandingListener extends MouseInputAdapter {
  @Override public void mouseDragged(MouseEvent e) {
    setFocusable(true);
    if(srcPoint==null) srcPoint = e.getPoint();
    Point destPoint = e.getPoint();
    polygon.reset();
    polygon.addPoint(srcPoint.x,  srcPoint.y);
    polygon.addPoint(destPoint.x, srcPoint.y);
    polygon.addPoint(destPoint.x, destPoint.y);
    polygon.addPoint(srcPoint.x,  destPoint.y);
    //setSelectedIndices(getIntersectsIcons(polygon));
    if(srcPoint.getX()==destPoint.getX() || srcPoint.getY()==destPoint.getY()) {
      line.setLine(srcPoint.getX(),srcPoint.getY(),destPoint.getX(),destPoint.getY());
      setSelectedIndices(getIntersectsIcons(line));
    }else{
      setSelectedIndices(getIntersectsIcons(polygon));
    }
    repaint();
  }
  @Override
  public void mouseReleased(MouseEvent e) {
    setFocusable(true);
    srcPoint = null;
    repaint();
  }
  @Override
  public void mousePressed(MouseEvent e) {
    int index = locationToIndex(e.getPoint());
    Rectangle rect = getCellBounds(index,index);
    if(!rect.contains(e.getPoint())) {
      getSelectionModel().setLeadSelectionIndex(getModel().getSize());
      clearSelection();
      setFocusable(false);
    }else{
      setFocusable(true);
    }
  }
  private int[] getIntersectsIcons(Shape p) {
    ListModel model = getModel();
    Vector< Integer > list = new Vector< Integer >(model.getSize());
    for(int i=0;i < model.getSize();i++) {
      Rectangle r = getCellBounds(i,i);
      if(p.intersects(r)) {
        list.add(i);
      }
    }
    int[] il = new int[list.size()];
    for(int i=0;i < list.size();i++) {
      il[i] = list.get(i);
    }
    return il;
  }
}

References

2008/06/25

aterai

Mouse Drag Auto Scrolling

Code

JLabel label = new JLabel();
//"CRW_3857_JFR.jpg" > http://sozai-free.com/
label.setIcon(new ImageIcon(getClass().getResource("CRW_3857_JFR.jpg")));
JScrollPane scroll = new JScrollPane(label,
    JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//*
ViewportDragScrollListener l = new ViewportDragScrollListener(label);
JViewport v = scroll.getViewport();
v.addMouseMotionListener(l);
v.addMouseListener(l);
v.addHierarchyListener(l);
/*/
//If label has its own MouseListeners, recommended to use ComponentDragScrollListener instead of ViewportDragScrollListener:
ComponentDragScrollListener l = new ComponentDragScrollListener(label);
label.addMouseMotionListener(l);
label.addMouseListener(l);
label.addHierarchyListener(l);
//*/
add(scroll);
scroll.setPreferredSize(new Dimension(320, 320));
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 javax.swing.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 javax.swing.Timer(DELAY, new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        JViewport vport = (JViewport)label.getParent();
        Point vp = vport.getViewPosition();
        vp.translate(move.x, move.y);
        label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
      }
    });
  }
  @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;
    Point vp = vport.getViewPosition();
    vp.translate(dx, dy);
    label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
    move.setLocation(SPEED*dx, SPEED*dy);
    startPt.setLocation(pt);
  }
  @Override public void mousePressed(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(hc); //label.setCursor(hc);
    startPt.setLocation(e.getPoint());
    move.setLocation(0, 0);
    scroller.stop();
  }
  @Override public void mouseReleased(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(dc); //label.setCursor(dc);
    scroller.start();
  }
  @Override public void mouseExited(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(dc); //label.setCursor(dc);
    move.setLocation(0, 0);
    scroller.stop();
  }
}
class ComponentDragScrollListener 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 javax.swing.Timer scroller;
  private final JComponent label;
  private Point startPt = new Point();
  private Point move    = new Point();

  public ComponentDragScrollListener(JComponent comp) {
    this.label = comp;
    this.dc = comp.getCursor();
    this.scroller = new javax.swing.Timer(DELAY, new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        Container c = label.getParent();
        if(c instanceof JViewport) {
          JViewport vport = (JViewport)c;
          Point vp = vport.getViewPosition();
          vp.translate(move.x, move.y);
          label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
        }
      }
    });
  }
  @Override public void hierarchyChanged(HierarchyEvent e) {
    JComponent jc = (JComponent)e.getSource();
    if((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED)!=0
       && !jc.isDisplayable()) {
      scroller.stop();
    }
  }
  @Override public void mouseDragged(MouseEvent e) {
    scroller.stop();
    JComponent jc = (JComponent)e.getSource();
    Container c = jc.getParent();
    if(c instanceof JViewport) {
      JViewport vport = (JViewport)jc.getParent();
      Point cp = SwingUtilities.convertPoint(jc,e.getPoint(),vport);
      int dx = startPt.x - cp.x;
      int dy = startPt.y - cp.y;
      Point vp = vport.getViewPosition();
      vp.translate(dx, dy);
      jc.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
      move.setLocation(SPEED*dx, SPEED*dy);
      startPt.setLocation(cp);
    }
  }
  @Override public void mousePressed(MouseEvent e) {
    scroller.stop();
    move.setLocation(0, 0);
    JComponent jc = (JComponent)e.getSource();
    jc.setCursor(hc);
    Container c = jc.getParent();
    if(c instanceof JViewport) {
      JViewport vport = (JViewport)c;
      Point cp = SwingUtilities.convertPoint(jc,e.getPoint(),vport);
      startPt.setLocation(cp);
    }
  }
  @Override public void mouseReleased(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(dc);
    scroller.start();
  }
  @Override public void mouseExited(MouseEvent e) {
    ((JComponent)e.getSource()).setCursor(dc);
    move.setLocation(0, 0);
    scroller.stop();
  }
}

References