我有一个 JEditorPane,我在上面放置了一个鼠标监听器,并且可以检测光标所在的位置。
但是,我希望能够获取光标所在行的文本。有我可以使用的实用方法吗?如果没有,那么我将如何构造一个方法来执行此操作?
xmlEditor.addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
try {
int caretPosition = xmlEditor.getCaretPosition();
int offset = 0;
int length = 0;
xmlEditor.getText(offset, length);
} catch (BadLocationException ex) {
Logger.getLogger(EZXPathFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
);
最佳答案
Is there a utility method I can use?
从未尝试过使用 JEditorPane,但您也许可以使用 Utilities
类。您应该能够使用 getRowStart(...)
和 getRowEnd(...)
等方法。一旦知道开始和结束偏移量,您就可以从 JEditorPane 获取文本。
类似于:
int start = Utilities.getRowStart(textComponent, offset);
int end = Utilities.getRowEnd(textComponent, offset);
String text = textComponent.getText(start, end-start);
关于java - 如何从 JEditorPane 获取光标当前所在行的行文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541213/