---
title: JTextAreaの任意の行まで移動
tags: [JTextArea, JScrollPane]
author: aterai
pubdate: 2006-10-02
description: 指定した行番号がJTextAreaの中で先頭にくるようにジャンプします。
---
* 概要 [#f76f67cc]
指定した行番号が`JTextArea`の中で先頭にくるようにジャンプします。

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

* サンプルコード [#he8c09bc]
#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 = 1;
    try {
      i = Integer.parseInt(textField.getText().trim());
      i = Math.max(1, Math.min(root.getElementCount(), i));
    } catch (NumberFormatException nfe) {
      Toolkit.getDefaultToolkit().beep();
      return;
    }
    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());
      //textArea.requestFocus();
    } catch (BadLocationException ble) {
      Toolkit.getDefaultToolkit().beep();
    }
  }
});
frame.getRootPane().setDefaultButton(button);
}}

* 解説 [#qa71cf1b]
上記のサンプルでは、任意の行番号を指定してKBD{Enter}キー、またはボタンをクリックすると、`1`から最大行数までの範囲で、その行が先頭にくるように表示位置が変更されます。

`JTextArea#setCaretPosition(int)`メソッドによるキャレットの位置変更だけでは、移動先を移動元より大きな行番号にした場合、`JTextArea`の下までしかスクロールしないので、`JTextArea#modelToView(int)`メソッドで取得した座標が出来るだけ上部にくるように処理しています。

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

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