java - 我可以在 Java 中识别光标所在的字符串吗?
问题描述
目前我正在研究一个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() 方法时,附加到特定单词的标点可能会产生意想不到的结果。像句号( . )这样的标点符号可以被认为是使用这些方法中的任何一种的单词,因此必须考虑防止它。
推荐阅读
- dapper - 对任意属性的 Dapper 查询
- mongodb - 如果我们有 10,000 个输入测试数据文件,如何减少磁盘空间
- python - 索引在 MongoDB 中的查找没有预期的那么快?
- ansible - “dict object”在 Ansible Playbook 中没有属性“stdout”
- mongodb - Mongo 查询 $out 在版本 4.0.4 中不起作用
- laravel - laravel 图像仅在视图中预览为缩略图,但在源页面中,存储链接是正确的
- java - 当 EditText 为空时防止 nullPointerException
- javascript - 从 React Native for Android 部署时出现 Jar 错误
- mysql - 使用同一行中的另一列值更新列的所有值,除非重复条目
- mysql - 使用播放框架从 mysql 读取并插入 mongo 的运行脚本问题(多线程问题)