i am looking for a function which gives the viewport starting line and viewport ending line from jtextarea. The below code works fine. But when the number of lines in the jtextarea is too big, say 10,000 lines, response of the cursor becoming very slow. I narrowed down the line which is causing it, it is,
startLine = getRow(topLeft, editorTextArea) - 1; //editorTextArea is jtextarea name
endLine = getRow(bottomRight, editorTextArea);
I am calling the startAndEndLine() on every keyPressEvent
Can someone suggest me a better code, which is efficient?
private void startAndEndLine() {
Rectangle r = editorTextArea.getVisibleRect();
Point topLeft = new Point(r.x, r.y);
Point bottomRight = new Point(r.x + r.width, r.y + r.height);
try {
startLine = getRow(topLeft, editorTextArea) - 1;
endLine = getRow(bottomRight, editorTextArea);
} catch (Exception ex) {
// System.out.println(ex);
}
}
public int getViewToModelPos(Point p, JTextComponent editor) {
int pos = 0;
try {
pos = editor.viewToModel(p);
} catch (Exception ex) {
}
return pos;
}
public int getRow(Point point, JTextComponent editor) {
int pos = getViewToModelPos(point, editor);
int rn = (pos == 0) ? 1 : 0;
try {
int offs = pos;
while (offs > 0) {
offs = Utilities.getRowStart(editor, offs) - 1;
rn++;
}
} catch (BadLocationException e) {
System.out.println(e);
}
return rn;
}
This is based on a solution by JigarJoshi from this question Java: column number and line number of cursor's current position ... You gotta love this site ;)
protected int getLineNumber(int modelPos) throws BadLocationException {
return textArea.getLineOfOffset(modelPos) + 1;
}
Rectangle viewRect = scrollPane.getViewport().getViewRect();
Point startPoint = viewRect.getLocation();
int pos = textArea.viewToModel(startPoint);
try {
int startLine = getLineNumber(pos);
Point endPoint = startPoint;
endPoint.y += viewRect.height;
pos = textArea.viewToModel(endPoint);
int endLine = getLineNumber(pos);
System.out.println(startLine + " - " + endLine);
} catch (BadLocationException exp) {
}
This is not entirely accurate, but gives you a starting point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With