csound
asked on
Get line number from caret position
I’m using JEditorPane and I want to know how get line number from caret position.
You must count the number of newlines in the result from JEditorPane.getText().
Then add 1 if the last character is not a newline, so
your 1st line numbers 1.
;JOOP!
Then add 1 if the last character is not a newline, so
your 1st line numbers 1.
;JOOP!
ASKER
Hmmm may be my question was not clear enough.
I have the following code which displays caret position every time the caret gets updated.
But now, I’m trying to modify that so that the JLabel displays in which line the caret is located.
protected class CaretListenerLabel extends JLabel implements CaretListener {
public CaretListenerLabel (String label) {
super(label);
}
public void caretUpdate(CaretEvent e) {
//Get the location in the text
int dot = e.getDot();
int mark = e.getMark();
if (dot == mark) { // no selection
try {
Rectangle caretCoords = editor.modelToView(dot);
//Convert it to view coordinates
setText("caret: text position: " + dot +
", view location = [" +
caretCoords.x + ", " + caretCoords.y + "]" +
nl);
} catch (BadLocationException ble) {
setText("caret: text position: " + dot + nl);
}
} else if (dot < mark) {
setText("selection from: " + dot + " to " + mark + nl);
} else {
setText("selection from: " + mark + " to " + dot + nl);
}
}
}
I have the following code which displays caret position every time the caret gets updated.
But now, I’m trying to modify that so that the JLabel displays in which line the caret is located.
protected class CaretListenerLabel extends JLabel implements CaretListener {
public CaretListenerLabel (String label) {
super(label);
}
public void caretUpdate(CaretEvent e) {
//Get the location in the text
int dot = e.getDot();
int mark = e.getMark();
if (dot == mark) { // no selection
try {
Rectangle caretCoords = editor.modelToView(dot);
//Convert it to view coordinates
setText("caret: text position: " + dot +
", view location = [" +
caretCoords.x + ", " + caretCoords.y + "]" +
nl);
} catch (BadLocationException ble) {
setText("caret: text position: " + dot + nl);
}
} else if (dot < mark) {
setText("selection from: " + dot + " to " + mark + nl);
} else {
setText("selection from: " + mark + " to " + dot + nl);
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If the caret is at the first position (e.g. top) of the jEditorPane, then the following code returns "0". If you move the caret/cursor down one line, the code returns "1":
jEditorPane1.getCaretPosit