I have the following requirements:
I need a scrollable JTextPane. The user may type into this text pane, or text may be inserted into it that is not typed by the user. Think something like an IM window. Although the window must be scrollable to allow the user to review text previously typed, the caret should never move from its position at the end of the text. Any text entered by the user will always appear at the end.
In JTextPane, when the user scrolls with the scroll bar, the caret does not move. The viewport is adjusted. However, when the user presses the up and down arrow keys, the JTextPane caret moves with it (whether the window scrolls or not).
What I want is that an up arrow key would function the same as moving the scroll bar up with the mouse. The arrow keys should have nothing to do with the caret.
I have tried the following approaches, without success: 1) add a "No-op" action to the Keymap for my text pane class (using JTextPane.addKeymap() and Keymap.addActionForKeyStroke()). This stops the caret from moving but prevents the action from being passed on to the Scroll Pane to scroll the view. 2) remove the arrow keys from the keymap for my text pane class. This affects all JTextPanes in my application which is not what I want.
What I want is to add an action to my TextPane keymap that simply calls the ScrollPane action for Up and Down arrow.
What is the best way to accomplish this?
A possibility that occurs to me is to implement a KeyListener (which receives the key stroke before the keymap) to trap these keys and then to implement the scrolling by hand. But this would seem to require me to compute font sizes, etc. Is there an easier way?
The ideal thing would be if there was some way to "anchor" the caret to whatever the end of the text was.