概要

JTableをスクロールバーではなく、内部の行をマウスでドラッグすることでスクロール可能になるよう設定します。

サンプルコード

class DragScrollingListener extends MouseAdapter {
  protected static final int VELOCITY = 5;
  protected static final int DELAY = 10;
  protected static final double GRAVITY = .95;
  protected final Cursor dc = Cursor.getDefaultCursor();
  protected final Cursor hc = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  protected final Timer scroller;
  protected final Point startPt = new Point();
  protected final Point delta = new Point();

  protected DragScrollingListener(JComponent c) {
    super();
    this.scroller = new Timer(DELAY, e -> {
      JViewport vport = (JViewport) SwingUtilities.getUnwrappedParent(c);
      Point vp = vport.getViewPosition();
      vp.translate(-delta.x, -delta.y);
      c.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
      if (Math.abs(delta.x) > 0 || Math.abs(delta.y) > 0) {
        delta.setLocation((int) (delta.x * GRAVITY), (int) (delta.y * GRAVITY));
      } else {
        ((Timer) e.getSource()).stop();
      }
    });
  }

  @Override public void mousePressed(MouseEvent e) {
    Component c = e.getComponent();
    c.setCursor(hc);
    c.setEnabled(false);
    Container p = SwingUtilities.getUnwrappedParent(c);
    if (p instanceof JViewport) {
      JViewport vport = (JViewport) p;
      Point cp = SwingUtilities.convertPoint(c, e.getPoint(), vport);
      startPt.setLocation(cp);
      scroller.stop();
    }
  }

  @Override public void mouseDragged(MouseEvent e) {
    Component c = e.getComponent();
    Container p = SwingUtilities.getUnwrappedParent(c);
    if (p instanceof JViewport) {
      JViewport vport = (JViewport) p;
      Point cp = SwingUtilities.convertPoint(c, e.getPoint(), vport);
      Point vp = vport.getViewPosition();
      vp.translate(startPt.x - cp.x, startPt.y - cp.y);
      delta.setLocation(VELOCITY * (cp.x - startPt.x), VELOCITY * (cp.y - startPt.y));
      ((JComponent) c).scrollRectToVisible(new Rectangle(vp, vport.getSize()));
      startPt.setLocation(cp);
    }
  }

  @Override public void mouseReleased(MouseEvent e) {
    Component c = e.getComponent();
    c.setCursor(dc);
    c.setEnabled(true);
    scroller.start();
  }
}
View in GitHub: Java, Kotlin

解説

参考リンク

コメント