Bob
Bob

Reputation: 11

How do I find the display location (x,y) of an offset in a JTextPane?

I have a DocumentListener that has access to the JTextPane containing the document. In some cases the DocumentListener wants to pop up a list of commands that start with the string entered by the user.

The DocumentEvent has the character offset, but I need to convert this into an X,Y location to properly position the popup.

Currently the code uses textPane.modelToView(offset) to get a rectangle to get the location, but this is throwing NullPointerExceptions at times.

Is there another way to do this conversion?

Upvotes: 1

Views: 197

Answers (2)

Paul
Paul

Reputation: 20061

Try JTextPane.modelToView. To go the other way you'd use JTextPane.viewToModel.

Oops...I missed the part where you said you were already using modelToView. I believe you can only use the conversion functions when your component is rendered and visible. Could that be causing your NPE?

Upvotes: 2

StanislavL
StanislavL

Reputation: 57381

Currently the code uses textPane.modelToView(offset) to get a rectangle to get the location, but this is throwing NullPointerExceptions at times.

Surround the popup showing and modelTOView() calls in the SwingUtilities.invokeLater. I guess sometime you ask for position but views layout is not finished yet.

Upvotes: 2

Related Questions