Search code examples
javaswingselectionjtextpane

Control selection/browsing in JTextPane


I have a JTestPane containing some text (obviously). When browsing the text using the keyboard, one typically uses control + right arrow to skip whole words. The default behavior in JTestPane consists in putting the caret right before the first character of the next word.

For example, let's consider the sentence "This is a sentence". Starting from postion 0, if I skip "This" and go to the next word (using CTRL+RIGHT), the caret will be in position 5, i.e. right before "is".

This is fine for browsing, but I don't like this behavior for text selection. In the application I'm working on, it would be much better if, when using SHFT+CTRL+RIGHT, I was selecting only "This" (without the extra space) rather than "This ", as it is by default. In other words, I want to select characters 0-3 instead of 0-4.

I didn't find much information about how to tweak Swing in order to get this kind of result. Up to now, I've tried registering a CaretListener to the JTestPane and manually shortening the selection in order to remove the trailing space when necessary. It didn't feel right though, and it didn't work well neither, since it prevented from selecting multiple words.

So, if anyone can point me in the right direction, I'll be more than happy.


Solution

  • Swing uses Key Binding to invoke an Action when a certain KeyStroke is invoked. See Key Bindings for a list of these bindings. As you can see the selection-next-word Action is invoked in this case, so you would need to provide a custom Action.

    You could look at the source code of the DefaultEditorKit - to see how this is implemented and just make the selection 1 less.

    Or maybe you can use the Wrapping Actions concept to wrap the original Action and then just invoke the setSelection() method of JTextPane to reset the selection to be 1 less than you need. Not sure what the easier approach will be.