JTextPane and “continuous” cursor

it’s not easy to work with Swing components. I’m working on a special editor, it consists from N JTextPanes glued together. They resize according to amount of text they have inside on order to avoid scrollbars. So far it wasn’t so complicated. But now I got complicated – I wanted to be able to “walk” freely through the JTextPanes – using only keyboard arrows.

First I implemented jumping between current and next/previous with TAB key, this was not a big deal. What’s the problem with arrows? Well – in order to have it working as expected you need to be able to find out whether you’re at the last line or not. One would guess that reading document structure would work but if you have lines longer then JTextPane width the “internal” lines and visual ones differ. One “internal” line could split into multiple visual lines.

In cases like this I simply go and study – study the libraries – this kind of check needs to be somewhere, right? So we only have to find it. After half an hour of searching I found something that could work:

int newpos = text.getUI ().getNextVisualPositionFrom (text, pos, Position.Bias.Forward, direction, bias);

(complete reference for UI is here:

text is JTextComponent, pos is current position, Position.Bias defines the direction (back/forward), direction is int defined in SwingUtils (SOUTH, NORTH, etc…) and bias is Bias[1] returned back. I don’t care about Biases – I just call it with desired direction and get new position. And if it’s the same like the original one we probably hit the border. Voila!

Leave a Reply

Your email address will not be published. Required fields are marked *