Brian T Hannan Brian T Hannan - 4 years ago 161
Java Question

How do I get the line text from a JEditorPane for the line where my cursor is currently positioned?

I have a JEditorPane and I put a mouse listener on it and can detect where the cursor is.

However, I would like to be able to get the text of the line where my cursor is. Is there a utility method I can use? If not, then how would I construct a method to do this?

new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
try {
int caretPosition = xmlEditor.getCaretPosition();
int offset = 0;
int length = 0;
xmlEditor.getText(offset, length);
} catch (BadLocationException ex) {
Logger.getLogger(EZXPathFrame.class.getName()).log(Level.SEVERE, null, ex);

Answer Source

Is there a utility method I can use?

Never tried it with a JEditorPane but you might be able to use the Utilities class. You should be able to use methods like getRowStart(...) and getRowEnd(...). Once you know the starting and ending offset you can get the text from the JEditorPane.

Something like:

int start = Utilities.getRowStart(textComponent, offset);
int end = Utilities.getRowEnd(textComponent, offset);
String text = textComponent.getText(start, end-start);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download