我正在寻找一个函数,它从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;
}
答案 0 :(得分:1)
这是基于JigarJoshi从这个问题Java: column number and line number of cursor's current position的解决方案......你一定要喜欢这个网站;)
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) {
}
这不完全准确,但为您提供了一个起点。