我正在努力实现我用Java开发的文本编辑器的自动完成功能.要实现自动完成,我需要所有已经输入编辑器的(不同的)单词。
一个直接的实现是将JTextComponent转换为字符串,然后再进行标记。相反,是否有一种方法可以记住最后一个非字母数字字符是在哪里输入的,开始记录这个字符串,直到另一个非字母数字字符被键入,然后将这个记录的字符串添加到我的自动完成字典中的单词集中?
/*Contains only parts of code that is relavant to the question*/
public class Editor {
private JFrame editorFrame;
/*this is where text typed is shown*/
private JTextComponent textComp;
/*autoComplete contains all words in the entered text*/
/*private TreeSet<String> autoComplete*/
/*private JMenu autoCompleteMenu*/
public static void main(String[] args) {
Editor editor = new Editor();
editor.Launch();
}
private void Launch() {
editorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editorFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
editorFrame.setVisible(true);
editorFrame.pack();
}
public Editor() {
editorFrame = new JFrame("Critter");
JTextArea ta = new JTextArea("", 46, 115);
ta.setLineWrap(true);
textComp = (JTextComponent)ta;
}
/*
Iam trying to implement the following
*/
/*
specialChars = {all special characters,space,tab}
if typed character is in specialChars:
while KeyEvent is alpha-numeric :
record KeyEvent to a string
search for this recorded string in autoComplete and create autoCompleteMenu of possible completions
if autoCompleteMenu != null:
display autoCompleteMenu
add string to autoComplete
*/
/*I want to know how to detect the keyevent belonging to specialChars and recording the string */
}
发布于 2015-04-10 11:32:58
除了输入外,还有粘贴操作,其中添加了多个字符。但是无论如何,您可以使用DocumentListener处理插入更新/远程更新/更改更新,并根据新添加的内容修改代码。DocumentEvent有偏移量/长度,所以您可以跟踪添加的文本。
为了避免在通知问题中发生变异,请在SwingUtilities.invokeLater()中调用
https://stackoverflow.com/questions/29560140
复制相似问题