gpt4 book ai didi

java - jtextarea 视口(viewport)中的第一行和最后一行

转载 作者:搜寻专家 更新时间:2023-11-01 00:51:49 25 4
gpt4 key购买 nike

我正在寻找一个函数,它从 jtextarea 给出视口(viewport)起始行和视口(viewport)结束行。下面的代码工作正常。但是当 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;
}

最佳答案

这是基于 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) {
}

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

关于java - jtextarea 视口(viewport)中的第一行和最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12060804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com