Swing/SmoothScroll のバックアップ(No.14)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/SmoothScroll へ行く。
- 1 (2007-08-13 (月) 13:01:23)
- 2 (2011-06-01 (水) 03:09:21)
- 3 (2013-02-01 (金) 11:28:46)
- 4 (2014-12-24 (水) 14:51:07)
- 5 (2016-03-27 (日) 19:51:07)
- 6 (2017-07-26 (水) 16:43:19)
- 7 (2018-07-27 (金) 16:27:58)
- 8 (2020-07-30 (木) 11:58:28)
- 9 (2021-12-21 (火) 16:30:51)
- 10 (2025-01-03 (金) 08:57:02)
- 11 (2025-01-03 (金) 09:01:23)
- 12 (2025-01-03 (金) 09:02:38)
- 13 (2025-01-03 (金) 09:03:21)
- 14 (2025-01-03 (金) 09:04:02)
- category: swing
folder: SmoothScroll
title: JTextAreaでSmoothScrollによる行移動
tags: [JScrollPane, JViewport, Animation, JTextArea]
author: aterai
pubdate: 2007-08-13T13:01:23+09:00
description: SmoothScrollアニメーション有りでJTextAreaの任意の行まで移動します。
image:
Summary
SmoothScroll
アニメーション有りでJTextArea
の任意の行まで移動します。
Screenshot

Advertisement
Source Code Examples
Document doc = textArea.getDocument();
Element root = doc.getDefaultRootElement();
int ln = model.getNumber().intValue();
try {
Element elem = root.getElement(ln - 1);
Rectangle dest = textArea.modelToView(elem.getStartOffset());
Rectangle current = scroll.getViewport().getViewRect();
new Timer(20, e -> {
Timer animator = (Timer) e.getSource();
if (dest.y < current.y && animator.isRunning()) {
int d = Math.max(1, (current.y - dest.y) / 2);
current.y = current.y - d;
textArea.scrollRectToVisible(current);
} else if (dest.y > current.y && animator.isRunning()) {
int d = Math.max(1, (dest.y - current.y) / 2);
current.y = current.y + d;
textArea.scrollRectToVisible(current);
} else {
textArea.setCaretPosition(elem.getStartOffset());
animator.stop();
}
}).start();
} catch (BadLocationException ex) {
UIManager.getLookAndFeel().provideErrorFeedback(textArea);
}
View in GitHub: Java, KotlinExplanation
上記のサンプルでは、java.swing.Timer
でイベントが発生するとscrollRectToVisible(...)
メソッドを使用して目的位置と現在位置の差の半分だけViewRect
のスクロールを繰り返すことで行移動アニメーションを行っています。