Google Tag Manager

2020/02/29

Display the Unicode code point of the character at the Caret position in the JTextArea

Code

String u1F60x = "😀😁😂😃😄😅😆😇😈😉😊😋😌😍😎😏";
String u1F61x = "😐😑😒😓😔😕😖😗😘😙😚😛😜😝😞😟";
String u1F62x = "😠😡😢😣😤😥😦😧😨😩😪😫😬😭😮😯";
String u1F63x = "😰😱😲😳😴😵😶😷😸😹😺😻😼😽😾😿";
String u1F64x = "🙀🙁🙂  🙅🙆🙇🙈🙉🙊🙋🙌🙍🙎🙏";

JTextField label = new JTextField();
label.setEditable(false);
label.setFont(label.getFont().deriveFont(32f));

List<String> l = Arrays.asList(u1F60x, u1F61x, u1F62x, u1F63x, u1F64x);
JTextArea textArea = new JTextArea(String.join("\n", l));
textArea.addCaretListener(e -> {
  try {
    int dot = e.getDot();
    int mark = e.getMark();
    if (dot - mark == 0) {
      Document doc = textArea.getDocument();
      String txt = doc.getText(dot, 1);
      int code = txt.codePointAt(0);
      if (Character.isHighSurrogate((char) code)) {
        txt = doc.getText(dot, 2);
        code = txt.codePointAt(0);
      }
      label.setText(String.format("%s: U+%04X", txt, code));
    } else {
      label.setText("");
    }
  } catch (BadLocationException ex) {
    ex.printStackTrace();
  }
});

References