0

我有一个看似很小的问题,但过去2天我找不到明确的答案。我正在创建一个自动完成拼写检查器来检查 JTextPane(称为mainTxtTypeArea)。我可以通过开始和结束索引获取用户正在处理的当前单词,但是当我只想突出显示一个特定单词时,荧光笔将继续超出键入的单词。这是文档事件发生时调用的代码:

public void checkWord(DocumentEvent e) {
            try {
                Highlighter redZigZag = mainTxtTypeArea.getHighlighter();
                int start = Utilities.getWordStart(mainTxtTypeArea, e.getOffset());
                int end = Utilities.getWordEnd(mainTxtTypeArea, e.getOffset());
                int length = end - start;
                String word = mainTxtTypeArea.getDocument().getText(start, length);

                if(dictionary.find(word) == false && Character.isWhitespace(word.charAt(0)) == false){
                    System.out.println("Incorrect: "+word);
                    //I found a zigzag highlighter online, but the default yields the same result
                    redZigZag.addHighlight(start, end, painter);
                } else {
                    System.out.println("Correct: "+word);
                }

            } catch (BadLocationException ex) {}
        }

我也对任何替代方案持开放态度。我尝试使用样式,但它会引发异常,因为样式不能应用于文档侦听器。

4

1 回答 1

1

好的,我找到了替代方案。我没有使用文档侦听器,而是使用 KeyReleased 操作事件来监视我的文本窗格,然后将拼写错误的单词设为红色斜体。代码如下:

private void mainTxtTypeAreaKeyReleased(java.awt.event.KeyEvent evt) {
    checkWord();
}

private void checkWord() {
    try {
        int start = Utilities.getWordStart(mainTxtTypeArea, mainTxtTypeArea.getCaretPosition());
        int end = Utilities.getWordEnd(mainTxtTypeArea, mainTxtTypeArea.getCaretPosition());
        int length = end - start;

        if(length > 0) {
            StyledDocument doc = mainTxtTypeArea.getStyledDocument();
            SimpleAttributeSet as = new SimpleAttributeSet();

            if(dictionary.find(doc.getText(start, length)) == false){
                StyleConstants.setItalic(as, true);
                StyleConstants.setForeground(as, Color.red);
            } else {
                StyleConstants.setItalic(as, false);
                StyleConstants.setForeground(as, Color.BLACK);
            }
            doc.setCharacterAttributes(start, length, as, false);
        }
    } catch (BadLocationException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}
于 2012-04-28T07:59:02.743 回答