Swing/SelectWordAction のバックアップ(No.8)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/SelectWordAction へ行く。
- 1 (2016-05-09 (月) 00:44:03)
- 2 (2016-05-14 (土) 14:56:38)
- 3 (2016-06-16 (木) 01:02:25)
- 4 (2017-09-17 (日) 18:09:29)
- 5 (2019-03-19 (火) 17:01:14)
- 6 (2019-11-18 (月) 02:08:49)
- 7 (2021-06-01 (火) 10:40:02)
- 8 (2025-01-03 (金) 08:57:02)
- 9 (2025-01-03 (金) 09:01:23)
- 10 (2025-01-03 (金) 09:02:38)
- 11 (2025-01-03 (金) 09:03:21)
- 12 (2025-01-03 (金) 09:04:02)
- 13 (2025-02-06 (木) 11:04:39)
- category: swing
folder: SelectWordAction
title: JTextAreaで単語選択を実行した場合の区切り文字を変更する
tags: [JTextArea, Segment, Document]
author: aterai
pubdate: 2016-05-09T00:37:01+09:00
description: JTextAreaで文字列のダブルクリックによる単語選択を実行した場合、単語の区切りとみなす文字を追加します。
image:
概要
JTextArea
で文字列のダブルクリックによる単語選択を実行した場合、単語の区切りとみなす文字を追加します。
Screenshot

Advertisement
サンプルコード
// @see javax.swint.text.Utilities.getWordStart(...)
int getWordStart(JTextComponent c, int offs) throws BadLocationException {
Element line = Optional.ofNullable(Utilities.getParagraphElement(c, offs))
.orElseThrow(() -> new BadLocationException("No word at " + offs, offs));
Document doc = c.getDocument();
int lineStart = line.getStartOffset();
int lineEnd = Math.min(line.getEndOffset(), doc.getLength());
int offs2 = offs;
Segment seg = SegmentCache.getSharedSegment();
doc.getText(lineStart, lineEnd - lineStart, seg);
if (seg.count > 0) {
BreakIterator words = BreakIterator.getWordInstance(c.getLocale());
words.setText(seg);
int wordPosition = seg.offset + offs - lineStart;
if (wordPosition >= words.last()) {
wordPosition = words.last() - 1;
words.following(wordPosition);
offs2 = lineStart + words.previous() - seg.offset;
} else {
words.following(wordPosition);
offs2 = lineStart + words.previous() - seg.offset;
for (int i = offs; i > offs2; i--) {
char ch = seg.charAt(i - seg.offset);
if (ch == '_' || ch == '-') {
offs2 = i + 1;
break;
}
}
}
}
SegmentCache.releaseSharedSegment(seg);
return offs2;
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、JTextArea
で文字列をダブルクリックした場合に実行される単語選択アクション(new TextAction(DefaultEditorKit.selectWordAction)
)を変更し、常に_
、-
記号で単語を区切るように設定しています。
Default
_
と-
は単語区切りにならず、AA-BB_CC
は一つの単語として選択される- 単語選択アクションはクリックした位置から単語の先頭と末尾を探す方法として
javax.swint.text.Utilities
のgetWordEnd(...)
とgetWordEnd(...)
メソッドを使用している
Break words: _ and -
_
と-
を単語区切りに追加し、AA-BB_CC
のBB
上でダブルクリックするとBB
のみ選択されるよう変更javax.swint.text.Utilities
のgetWordEnd(...)
とgetWordEnd(...)
メソッドをコピーし、BreakIterator.getWordInstance(c.getLocale())
で見つけた単語内に_
か-
が存在するか再度検索するよう改変