Swing/GotoLine のバックアップソース(No.6)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- バックアップ を表示
- Swing/GotoLine へ行く。
- 1 (2007-08-13 (月) 13:00:53)
- 2 (2012-08-02 (木) 16:16:23)
- 3 (2013-02-22 (金) 19:04:09)
- 4 (2013-07-26 (金) 02:03:45)
- 5 (2014-12-26 (金) 15:45:54)
- 6 (2016-04-15 (金) 12:47:30)
- 7 (2016-09-17 (土) 20:54:42)
- 8 (2017-02-09 (木) 14:00:03)
- 9 (2017-02-09 (木) 15:23:16)
- 10 (2017-12-23 (土) 16:26:08)
- 11 (2018-10-14 (日) 16:40:50)
- 12 (2020-10-11 (日) 20:20:40)
- 13 (2022-07-14 (木) 10:41:58)
--- 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