• 追加された行はこの色です。
  • 削除された行はこの色です。
#navi(../)
*JScrollPaneのオートスクロール [#h85af000]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-11-22~
更新日:&lastmod;

#contents
**概要 [#d87718d8]
JScrollPane上のマウスポインタに応じてラベルをオートスクロールします。

http://terai.xrea.jp/swing/autoscroll/screenshot.png

**サンプルコード [#nf7c2bf6]
 private void autoScroll(Point ptLabel) {
   Point ptScroll = SwingUtilities.convertPoint(label, ptLabel, scroll);
   int iv = (int) scroll.getPreferredSize().getHeight();
   if(ptScroll.y < iv/2) {
     rect.setRect(0, ptLabel.y-ptScroll.y-SCROLL, 0, SCROLL);
     flg = true;
   }else{
     rect.setRect(0, ptLabel.y-ptScroll.y+iv+SCROLL, 0, SCROLL);
     flg = false;
 final JViewport vport = scroll.getViewport();
 scroller = new javax.swing.Timer(5, new ActionListener() {
   public void actionPerformed(ActionEvent e) {
     Rectangle vr = vport.getViewRect();
     int w = vr.width;
     int h = vr.height;
     Point pt = SwingUtilities.convertPoint(vport,0,0,label);
     rect.setRect(pt.x+point.x, pt.y+point.y, w, h);
     label.scrollRectToVisible(rect);
   }
   scroller.start();
 }
 });
 vport.addMouseMotionListener(new MouseMotionAdapter() {
   public void mouseMoved(MouseEvent e) {
     scroller.stop();
     Point pt = e.getPoint();
     point.setLocation(SCROLL*(pt.x-startPoint.x), SCROLL*(pt.y-startPoint.y));
     scroller.start();
     startPoint.setLocation(pt);
   }
 });

-[[サンプルを起動>http://terai.xrea.jp/swing/autoscroll/sample.jnlp]]
-[[jarファイル>http://terai.xrea.jp/swing/autoscroll/sample.jar]]
-[[ソース>http://terai.xrea.jp/swing/autoscroll/src.zip]]

**解説 [#i40d83e6]
上記のサンプルでは、マウスポインタの位置に応じて、上下方向にのみ一定速度で自動スクロールします。SwingUtilities.convertPoint()メソッドを使って座標の変換を行っています。
上記のサンプルでは、JViewport内の画像ラベルがマウスポインタの移動方向と距離に応じて自動的にスクロールします。マウスをクリックすると一時停止します。

javax.swing.Timerを使うことでスクロールの開始、継続、停止を行っています。

JTextPaneで文字列を挿入したときに、最後まで自動スクロールしたい場合は、[[JTextPaneで最終行に移動>Swing/CaretPosition]]を参考にしてください。

**参考リンク [#j6c969ff]
-[[JTextPaneで最終行に移動>Swing/CaretPosition]]
-[[2000ピクセル以上のフリー写真素材集>http://sozai-free.com/]]

**コメント [#paa26bcc]
#comment