title: Get caret position when key pressed using KeyboardFocusManager
body: <p>I'm trying to get the current caret position when the "&lt;" character is typed, using a KeyboardFocusManager. Code below. If the text field is empty when they character is typed I would expect the caret position to be 0. However, the result I actually get is this: 0   0   1. Could anyone explain why this is happening?</p>
  
  <pre><code>import java.awt.KeyEventDispatcher;
  import java.awt.KeyboardFocusManager;
  import java.awt.event.KeyEvent;
  
  import javax.swing.*;
  
  
  public class TextEditor {
  
      @SuppressWarnings("serial")
      public static class TextClass extends JTextArea {
  
          static int startpos = 0; 
  
          public boolean checkKeyTyped (KeyEvent e) {
              String keystr = Character.toString(e.getKeyChar());
              switch (keystr) {
                  case "&lt;":
                      startpos = getSelectionStart();
                      System.out.print("   " + startpos);
              }
              return false;
          }
      }       
  
      public static void main(String[] args) {
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(300, 200);
          frame.setLocationRelativeTo(null);
          final JTextArea textArea = new TextClass();
          frame.add(textArea);
          frame.setVisible(true);
  
          // Add keyboard listener
  
          KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
              public boolean dispatchKeyEvent(KeyEvent e) {
                  return ((TextClass) textArea).checkKeyTyped(e);
              }
          });
      }
  }
  </code></pre>