[英]How to find out line numbers of selected text?
Assume this very small program: 假设这个非常小的程序:
1. package ex1;
2. public interface Resizable {
3. void resize();
4. }
In my editor, if I select line 2-3 using mouse and say click on a button, I want to highlight these texts and also print, which line numbers were selected exactly for the button. 在我的编辑器中,如果我使用鼠标选择第2-3行并说按一个按钮,我想突出显示这些文本并打印,这些行号是为按钮选择的。
I can do the highlighting part, but I don't know how to find the line numbers of highlighted texts, As I think, I should use a listener, which will detect any changes in editor. 我可以做突出显示部分,但我不知道如何找到突出显示文本的行号。我认为,我应该使用一个侦听器,它将检测编辑器中的任何更改。
I think I should use an action listener, which will detect when the button is pressed after selecting text blocks. 我想我应该使用一个动作监听器,它会在选择文本块后检测按钮的按下时间。 But how I will know, which lines are selected exactly? 但我怎么知道,选择哪条线呢?
The start and end of the highlight can be taken from the caret position dot
and mark
respectively. 突出显示的开始和结束可分别从插入符号位置dot
和mark
。 These are offsets in the Document
. 这些是Document
中的偏移量。 You must then calculate the number of newlines from the start of the document until the mark/do 然后,您必须计算从文档开头到标记/做的换行符数
textArea.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
int startLine = getLine(e.getDot());
int endLine = getLine(e.getMark());
...
}
});
private int getLine(int offset) {
String text = textArea.getDocument().getText(0, offset);
int linenr = 0;
int idx = text.indexOf("\n");
while (idx != -1) {
linenr++;
idx = text.indexOf("\n", idx);
}
return linenr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.