• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JScrollPaneのViewPortをマウスで掴んでスクロール
#navi(../)
RIGHT:Posted by [[terai]] at 2006-01-02
*JScrollPaneのViewPortをマウスで掴んでスクロール [#ef47828b]
JScrollPaneの窓の中をマウスで掴んで画像をスクロールします。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#e92a8d9e]
#code{{
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);
    //vport.setViewPosition(vp);
    label.scrollRectToVisible(
      new Rectangle(vp, vport.getSize()));
    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();
  }
}
}}

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

**参考リンク [#b337b5bb]
-[[JScrollPaneのオートスクロール>Swing/AutoScroll]]
-[[2000ピクセル以上のフリー写真素材集>http://sozai-free.com/]]
--大きな''猫''写真があったので拝借しています。
-[[Bug ID: 6333318 JViewPort.scrollRectToVisible( Rectangle cr ) doesn't scroll if cr left or above>http://bugs.sun.com/view_bug.do?bug_id=6333318]]

**コメント [#ubd1d4e0]
- つかんで移動ということですが、移動方向が逆の気がします。 -- [[名無し]] &new{2006-02-25 (土) 01:24:46};
-- ご指摘ありがとうございます。確かに逆ですね。画像を掴んでというより、スクロールバーを掴んでみたいな動きになってました。修正しておきます。 -- [[terai]] &new{2006-02-25 (土) 03:33:50};
- SwingUtilities.convertPointの代わりに、vport.getViewPosition()を使用するように変更。スクリーンショットの更新。 -- [[terai]] &new{2009-01-19 (Mon) 16:58:27};

#comment