Java caret position - Getting the caret position in a text document

Java caret position FAQ: How do I get the Java caret position in a JTextComponent, such as a JTextArea or JEditorPane?

Wow, this was a bear to find anything about. Everyone always wants to show you how to use a JPopupMenu with a mouse click, such as a right-mouse click, but nobody ever shows you how to display a JPopupMenu when someone uses a keystroke, or keyboard accelerator.

So, using a little Java mojo, here is how I get the caret position in a JTextComponent (JTextArea, etc.) to display a JPopupMenu near the current caret position:

  void edit_PopupMenuMenuItem_actionPerformed(ActionEvent e)
  {
    // i know that "show" is deprecated, but i could not get this to work
    // any other way
    Point point = jEditorPane.getCaret().getMagicCaretPosition();
    jPopupMenu1.show( jEditorPane,
                      (int)point.getX(),
                      (int)point.getY());
    jPopupMenu1.requestFocus();
    jPopupMenu1.grabFocus();
  }

If someone else sees this code, and knows of a better way to do this, please let me know. For now, I'm going with this, because it works pretty well.

 

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.