Swing/GotoLine のバックアップ差分(No.9)
- バックアップ一覧
- 現在との差分 を表示
- 現在との差分 - 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)
- 追加された行はこの色です。
- 削除された行はこの色です。
--- category: swing folder: GotoLine title: JTextAreaの任意の行まで移動 tags: [JTextArea, JScrollPane] 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 = 1; int i = Integer.parseInt(textField.getText().trim()); i = Math.max(1, Math.min(root.getElementCount(), i)); 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); 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(); } catch (BadLocationException ex) { Toolkit.getDefaultToolkit().beep(); } } }); frame.getRootPane().setDefaultButton(button); EventQueue.invokeLater(() -> getRootPane().setDefaultButton(button)); }} * 解説 [#explanation] 上記のサンプルでは、任意の行番号を指定してKBD{Enter}キー、またはボタンをクリックすると、その行が`JViewport`の表示範囲の最上部に配置されるよう表示領域を更新します。 `JTextArea#setCaretPosition(int)`メソッドによるキャレットの位置変更だけでは、移動先を移動元より大きな行番号にした場合、`JTextArea`の下部までしかスクロールしないので、`JTextArea#modelToView(int)`メソッドで取得した座標が出来るだけ上部にくるように処理しています。 `JTextArea#setCaretPosition(int)`メソッドによる`Caret`の位置変更だけでは、移動先を移動元より大きな行番号にした場合、`JTextArea`の下部までしかスクロールしないので、`JTextArea#modelToView(int)`メソッドで取得した座標が出来るだけ上部にくるように処理しています。 * 参考リンク [#reference] - [[JTextAreaでSmoothScrollによる行移動>Swing/SmoothScroll]] * コメント [#comment] #comment #comment