I'm currently writing a customized text editor in Java, and as part of that, I want to make it easy for the user to increase or decrease the font size in the text editing area (technically a JTextPane). I didn't expect this to be easy, but I've been pleasantly surprised that the following approach seems to work just fine:
A little ditty on how to find the caret position in a JTextComponent, and display a JPopupMenu near that position. This is one of those things that may not be 100% correct, but it works until someone finds a better way.
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: