簡體   English   中英

JEdi​​torPane獲取行和列號處字符的位置

[英]JEditorPane get position for character at line and column number

如何從給定的行和列中獲取與setCaret一起使用的Position?

該組件只有一種字體,並且是等寬的。 我見過的大多數其他答案都是用於確定給定位置的行號和列號。 我正在尋找相反的情況。

我確實看到了JTextComponent.viewToModel,但走不遠了。 必須有一種快速的方法嗎? :-)

使用DocumentElement結構獲取指定行的起始偏移量,然后僅添加要將插入號定位在的列:

Element root = component.getDocument().getDefaultRootElement();
int startOfLineOffset = root.getElement( line - 1 ).getStartOffset();
component.setCaretPosition( startOfLineOffset  + column);

您可以獲得行高和字符寬度。 使用modelToView()返回的矩形獲取行高,位置0和位置1的x差獲得x。 然后使用viewToModel()傳遞y=rowHeight*rowNumberx=charWidth*colNumber

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM