TITLE:JScrollPaneのViewPortをマウスで掴んでスクロール

JScrollPaneのViewPortをマウスで掴んでスクロール

編集者:Terai Atsuhiro
作成日:2006-01-02
更新日:2022-09-14 (水) 05:19:41

概要

JScrollPaneの窓の中をマウスで掴んで画像をスクロールします。

#screenshot

サンプルコード

final Cursor cc = label.getCursor();
final Cursor hc = new Cursor(Cursor.HAND_CURSOR);
final JViewport vport = scroll.getViewport();
vport.addMouseMotionListener(new MouseMotionAdapter() {
  public void mouseDragged(final MouseEvent e) {
    Rectangle vr = vport.getViewRect();
    int w = vr.width;
    int h = vr.height;
    int x = e.getX();
    int y = e.getY();
    Point pt = SwingUtilities.convertPoint(vport,0,0,label);
    rect.setRect(pt.x-x+startX, pt.y-y+startY, w, h);
    label.scrollRectToVisible(rect);
    startX = x;
    startY = y;
  }
});
vport.addMouseListener(new MouseAdapter() {
  public void mousePressed(MouseEvent e) {
    startX = e.getX();
    startY = e.getY();
    label.setCursor(hc);
  }
  public void mouseReleased(MouseEvent e) {
    label.setCursor(cc);
    label.repaint();
  }
});
  • &jnlp;
  • &jar;
  • &zip;

解説

JViewportの原点を中のJLabel(画像)の座標に、SwingUtilities.convertPointメソッドを使って変換し、これをマウスの移動した分だけずらした領域を、JComponent#scrollRectToVisibleメソッドで表示しています。

参考リンク

コメント

  • つかんで移動ということですが、移動方向が逆の気がします。 -- 名無し
  • 確かに逆ですね。画像を掴んでというより、スクロールバーを掴んでみたいな動きになってました。修正しておきます。 -- terai