概要

JTextArea内のCaret位置にある文字のUnicodeブロック(文字種)を取得してJTextFieldに表示します。

サンプルコード

JTextArea textArea = new JTextArea("😀😁😂てすとテストTESTtest試験、𠮟┷→");
textArea.addCaretListener(e -> {
  try {
    int loc = Math.min(e.getDot(), e.getMark());
    Document doc = textArea.getDocument();
    String txt = doc.getText(loc, 1);
    int code = txt.codePointAt(0);
    if (Character.isHighSurrogate((char) code)) {
      txt = doc.getText(loc, 2);
      code = txt.codePointAt(0);
    }
    Character.UnicodeBlock unicodeBlock = Character.UnicodeBlock.of(code);
    label.setText(String.format("%s: U+%04X", txt, code));
    labelUnicodeBlock.setText(Objects.toString(unicodeBlock));
  } catch (BadLocationException ex) {
    // should never happen
  }
});
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、JTextAreaCaretListenerを設定してCaret位置、または選択文字列の先頭文字にある文字のUnicodeコードポイントを取得し、Character.UnicodeBlock.of(int)メソッドを使用してその文字種(Unicodeブロック)をJTextFieldに表示しています。

参考リンク

コメント