Summary

JTextComponentなどで使用中のインプット・メソッドが変換のために使用可能な場合はCaretの色を変更するよう設定します。

Source Code Examples

JTextArea textArea = new JTextArea() {
  @Override public void updateUI() {
    super.updateUI();
    Caret caret = new InputContextCaret();
    caret.setBlinkRate(UIManager.getInt("TextArea.caretBlinkRate"));
    setCaret(caret);
  }
};

//...
class InputContextCaret extends DefaultCaret {
  private final Color caretFg = UIManager.getColor("TextArea.caretForeground");

  @Override public void paint(Graphics g) {
    if (isVisible()) {
      JTextComponent c = getComponent();
      boolean b = c.getInputContext().isCompositionEnabled();
      c.setCaretColor(b ? Color.RED : caretFg);
    }
    super.paint(g);
  }
}
View in GitHub: Java, Kotlin

Description

  • DefaultCaret#paint(...)をオーバーライドして、JTextComponent#getInputContext()InputContextを取得
  • 取得したInputContextで現在のインプット・メソッドが変換のために使用可能かをInputContext#isCompositionEnabled()で判別
    • ON: 使用可能の場合はCaretの色をCaret#setCaretColor(Color.RED)で変更
      • 入力途中のCaret色や下点線の変更方法が見つからない → 調査中
    • OFF: 使用可能の場合はCaretの色をCaret#setCaretColor(UIManager.getColor("TextArea.caretForeground"))で戻す
      • TextField.caretForegroundPasswordField.caretForegroundTextPane.caretForegroundEditorPane.caretForegroundなどで他のJTextComponentCaretデフォルト色を個別に取得可能
  • InputMethodListener (Java Platform SE 8)では現在のインプット・メソッドの使用可・不可の切り替えを取得できない?

Reference

Comment