我可以在Java中标识光标所在的字符串吗?

我可以在Java中标识光标所在的字符串吗?,java,events,mouselistener,Java,Events,Mouselistener,目前我正在从事一个Java项目。但要做到这一点,我想从游标中读取字符串,也就是说,我想读取游标当前所在的字符串。我怎样才能做到这一点?不太清楚您将文本插入符号(光标)放置在什么位置。下面的示例方法假设光标放置在Swing文本组件中显示的文本中包含的单词上,如JTextField、JTextArea、JEditPane等,这些单词在您自己的应用程序项目中可见。该类可以获取所需的数据 public static String getWordAtCaret(JTextComponent tc) {

目前我正在从事一个Java项目。但要做到这一点,我想从游标中读取字符串,也就是说,我想读取游标当前所在的字符串。我怎样才能做到这一点?

不太清楚您将文本插入符号(光标)放置在什么位置。下面的示例方法假设光标放置在Swing文本组件中显示的文本中包含的单词上,如JTextFieldJTextAreaJEditPane等,这些单词在您自己的应用程序项目中可见。该类可以获取所需的数据

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()方法时,附加到特定单词的标点符号可能会产生意外结果。类似句点()的标点符号可以被视为使用上述任何一种方法的单词,因此必须考虑防止出现这种情况。

请提供示例代码,显示您自己尝试过的内容。事实上,由于此问题,我无法启动我的项目。事实上,我不知道如何做这个特定的工作。你想读什么字符串?例如,您是否希望在应用程序窗口中显示一些字符串,然后能够检测用户何时单击其中一个字符串?实际上,屏幕上会有一些单词,如果我将光标放在任何单词下,光标将读取该单词并返回该单词….@Evan-
,实际上,屏幕上会出现一些文字…
-根据您最后的评论,您已经将一些相对简单的内容转换为一些相对复杂的内容。这到底是什么意思?你是指任意应用中的一些词吗?或者,您的意思是在您自己的应用程序中,可能在JTextArea或JEditPane中?我想开发一个Java应用程序,它可以翻译光标所在的任何单词。如果我只在后台运行我的应用程序,那么光标将扮演翻译的角色。所以我想用游标读取字符串。