5

我正在寻找一个函数,它从 jtextarea 提供视口起始线和视口结束线。下面的代码工作正常。但是当 jtextarea 中的行数太大时,比如 10,000 行,光标的响应会变得很慢。我缩小了导致它的范围,它是,

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

我在每个 keyPressEvent 上调用 startAndEndLine()

有人可以建议我一个更好的代码,这是有效的吗?

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;
}
4

1 回答 1

1

这是基于 JigarJoshi 从这个问题Java 中的解决方案:光标当前位置的列号和行号......你一定会喜欢这个网站;)

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) {
}

这并不完全准确,但为您提供了一个起点。

于 2012-08-21T20:58:56.477 回答