First line and last line in jtextarea viewport

I am looking for a function that gives the start and end line of a viewport from jtextarea. The code below is working fine. But when the number of lines in jtextarea is too large, say 10,000 lines, the cursor reaction becomes very slow. I narrowed the line that calls it, this,

 startLine = getRow(topLeft, editorTextArea) - 1; //editorTextArea is jtextarea name
 endLine = getRow(bottomRight, editorTextArea);

I call startAndEndLine () on every keyPressEvent

Can someone suggest me the best code that 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;
}
+5
source share
1 answer

This is based on JigarJoshi's solution from this Java question : column number and line number of the current cursor position ... You should 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.

+1
source

All Articles