---
category: swing
folder: GotoLine
title: JTextAreaの任意の行まで移動
tags: [JTextArea, JScrollPane, Caret]
author: aterai
pubdate: 2006-10-02T01:43:48+09:00
description: 指定した行番号がJTextAreaの中で先頭にくるようにジャンプします。
image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTNdpDdyKI/AAAAAAAAAa0/cOjr09yncHI/s800/GotoLine.png
---
* 概要 [#summary]
指定した行番号が`JTextArea`の中で先頭にくるようにジャンプします。

#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTNdpDdyKI/AAAAAAAAAa0/cOjr09yncHI/s800/GotoLine.png)

* サンプルコード [#sourcecode]
#code(link){{
JButton button = new JButton(new AbstractAction("Goto Line") {
  @Override public void actionPerformed(ActionEvent e) {
    Document doc = textArea.getDocument();
    Element root = doc.getDefaultRootElement();
    int i = Integer.parseInt(textField.getText().trim());
    i = Math.max(1, Math.min(root.getElementCount(), i));
    try {
      Element elem = root.getElement(i - 1);
      Rectangle rect = textArea.modelToView(elem.getStartOffset());
      Rectangle vr = scroll.getViewport().getViewRect();
      rect.setSize(10, vr.height);
      textArea.scrollRectToVisible(rect);
      textArea.setCaretPosition(elem.getStartOffset());
    } catch (BadLocationException ex) {
      Toolkit.getDefaultToolkit().beep();
    }
  }
});
EventQueue.invokeLater(() -> getRootPane().setDefaultButton(button));
}}

* 解説 [#explanation]
上記のサンプルでは、`JTextField`に任意の行番号を指定してKBD{Enter}キー、またはボタンをクリックすると、その行が`JViewport`の表示範囲の最上部に配置されるよう表示領域を更新します。

- `JTextArea#setCaretPosition(int)`メソッドによる`Caret`の位置変更だけでは、移動先を移動元より大きな行番号にした場合は`JTextArea`の下部までしかスクロールしない
- そのため`Caret`の位置変更のまえに、`JTextArea#modelToView(int)`メソッドで取得した座標が可能なかぎり上部にくるように`JTextArea#scrollRectToVisible(...)`メソッドで表示位置を変更

* 参考リンク [#reference]
- [[JTextAreaでSmoothScrollによる行移動>Swing/SmoothScroll]]

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