目前,我正在研究Java项目。但是要做到这一点,我想从游标中读取字符串,即我想读取当前放置游标的字符串。我该怎么办?
尚不清楚您将文本插入标记(光标)放置在的确切位置。下面的示例方法假定光标位于Swing文本组件(如JTextField,JTextArea,JEditPane等中显示的文本中包含的单词上,在< [拥有应用程序项目。 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()方法时,附加到特定单词的标点符号可能会提供意外的结果。可以使用这两种方法将标点符号如句点(。)视为一个单词,因此必须考虑一些防止这种现象的出现。注: