---
category: swing
folder: UnicodeBlock
title: JTextArea内の文字の文字種を取得する
tags: [JTextArea, Caret, Character]
author: aterai
pubdate: 2020-06-22T02:43:05+09:00
description: JTextArea内のCaret位置にある文字のUnicodeブロック(文字種)を取得してJTextFieldに表示します。
image: https://drive.google.com/uc?id=1GOMN2Ar0unSeCHDsTEHGWIRcm0DgABQz
---
* 概要 [#summary]
JTextArea内のCaret位置にある文字のUnicodeブロック(文字種)を取得してJTextFieldに表示します。

#download(https://drive.google.com/uc?id=1GOMN2Ar0unSeCHDsTEHGWIRcm0DgABQz)

* サンプルコード [#sourcecode]
#code(link){{
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
  }
});
}}

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

- `Unicode`コードポイントの取得は、サロゲートペアに対応
-- 参考: [[JTextArea内にあるCaret位置の文字のUnicodeコードポイントを表示する>Swing/CodePointAtCaret]]
- このサンプルでは、`EMOTICONS`、`HIRAGANA`、`KATAKANA`、`HALFWIDTH_AND_FULLWIDTH_FORMS`、`BASIC_LATIN`、`CJK_UNIFIED_IDEOGRAPHS`、`CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B`、`BOX_DRAWING`、`ARROWS`などの文字種が確認可能

* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/java/lang/Character.UnicodeBlock.html Character.UnicodeBlock (Java Platform SE 8)]
- [[JTextArea内にあるCaret位置の文字のUnicodeコードポイントを表示する>Swing/CodePointAtCaret]]

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