gpt4 book ai didi

java - 在 JTextComponent 中的每个非字母数字字符处对文本进行标记

转载 作者:行者123 更新时间:2023-12-01 11:40:32 26 4
gpt4 key购买 nike

我正在尝试为我用 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 */
}

最佳答案

除了打字之外,还有粘贴操作,其中添加了多个字符。但无论如何,您可以使用 DocumentListener 处理 insertUpdate/removeUpdate/changedUpdate 并根据新添加的内容调整您的代码。DocumentEvent 具有偏移量/长度,因此您可以跟踪添加的文本。

为了避免尝试在通知问题中发生变化,请将您的调用包装在 SwingUtilities.invokeLater() 中

关于java - 在 JTextComponent 中的每个非字母数字字符处对文本进行标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29560140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com