首页 > 解决方案 > 我可以在 Java 中识别光标所在的字符串吗?

问题描述

目前我正在研究一个Java项目。但要做到这一点,我想从光标读取字符串,即我想读取当前放置光标的字符串。我怎样才能做到这一点?

标签: javaeventsmouselistener

解决方案


目前还不清楚您将文本插入符号(光标)放在哪里。下面的示例方法假定光标位于 Swing 文本组件(如JTextFieldJTextAreaJEditPane等)中显示的文本中包含的单词上,该组件可在您自己的应用程序项目中查看。javax.swing.text.Utilities类可以获取你想要的数据。

public static String getWordAtCaret(JTextComponent tc) {
    String res = null;
    try {
        int caretPosition = tc.getCaretPosition();
        int startIndex = Utilities.getWordStart(tc, caretPosition);
        int endIndex = Utilities.getWordEnd(tc, caretPosition);
        res = tc.getText(startIndex, endIndex - startIndex);
    }
    catch (BadLocationException ex) {
        // Purposely Ignore so as to return null.
        // Do what you want with the exception if you like.
    }
    return res;
}

public static String getNextWordFromCaret(JTextComponent tc) {
    String res = null;
    try {
        int caretPosition = Utilities.getNextWord(tc, tc.getCaretPosition());
        int startIndex = Utilities.getWordStart(tc, caretPosition);
        int endIndex = Utilities.getWordEnd(tc, caretPosition);
        res = tc.getText(startIndex, endIndex - startIndex);
    }
    catch (BadLocationException ex) {
        // Purposely Ignore so as to return null.
        // Do what you want with the exception if you like.
    }
    return res;
}

public static String getPreviousWordFromCaret(JTextComponent tc) {
    String res = null;
    try {
        int caretPosition = Utilities.getPreviousWord(tc, tc.getCaretPosition()) - 2;
        int startIndex = Utilities.getWordStart(tc, caretPosition);
        int endIndex = Utilities.getWordEnd(tc, caretPosition);
        res = tc.getText(startIndex, endIndex - startIndex);
    }
    catch (BadLocationException ex) {
        // Purposely Ignore so as to return null.
        // Do what you want with the exception if you like.
    }
    return res;
}

注意:当使用 getNextWordFromCaret() 或 getPreviousWordFromCaret() 方法时,附加到特定单词的标点可能会产生意想不到的结果。像句号( . )这样的标点符号可以被认为是使用这些方法中的任何一种的单词,因此必须考虑防止它。


推荐阅读