我有一个看似很小的问题,但过去两天我找不到明确的答案。我正在创建一个自动完成的拼写检查程序,用于检查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) {}
}
我也对任何替代方案持开放态度。我尝试使用样式,但它会引发异常,因为样式不能应用于文档侦听器。
答案 0 :(得分: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);
}
}