TITLE:JScrollPaneのViewPortをマウスで掴んでスクロール
#navi(../)
*JScrollPaneのViewPortをマウスで掴んでスクロール [#ef47828b]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2006-01-02~
更新日:&lastmod;

#contents

**概要 [#id739e63]
JScrollPaneの窓の中をマウスで掴んで画像をスクロールします。

#screenshot

**サンプルコード [#e92a8d9e]
#code{{
 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;

**解説 [#bf42cf21]
JViewportの原点(左上)をSwingUtilities.convertPointメソッドを使って中のJLabel(画像)の座標に変換して基準のPoint座標としています。このPointをマウスの移動量に応じて変更し、JComponent#scrollRectToVisibleメソッドの引数として使用しています。

**参考リンク [#b337b5bb]
-[[2000ピクセル以上のフリー写真素材集>http://sozai-free.com/]]
--大きな''猫''写真があったので拝借しています。

**コメント [#ubd1d4e0]
- つかんで移動ということですが、移動方向が逆の気がします。 -- [[名無し]] &new{2006-02-25 (土) 01:24:46};
- 確かに逆ですね。画像を掴んでというより、スクロールバーを掴んでみたいな動きになってました。修正しておきます。 -- [[terai]] &new{2006-02-25 (土) 03:33:50};

#comment