Noxid said:
How should I set up a JTextPane so that the syntax highlighter can re-colour it when you change the text by typing or pasting something or whatever?
Uh, lemme think.
I used the Style class (
http://www.exampledepot.com/egs/javax.swing.text/style_HiliteWords2.html) to make syntax highlighting in the Assembler.
This is what I did to make it activate upon typing:
Code:
private void textBoxKeyReleased(java.awt.event.KeyEvent evt) {
if (useSyntaxColorsCheckBox.isSelected())
[COLOR="DarkGreen"]syntaxObj1.styleAsmCodeInLine(textBox,textBox.getCaretPosition());[/COLOR]
}
Whenever a key on the keyboard is released by the user, I use my syntax object (see file SyntaxColorTools.java in the Assembler source code) to colorize the syntax for the current line (but NOT for the whole document, because that is really slow).
[I used keyRelease instead of keyPress because keyPress causes chronological issues - checking for a typed character when the character does not exist yet.]
When a paste occurs, you have to recolor the whole document, or the at the very least, the chunk of text that was pasted.
This is what I did. I removed the default Ctrl+V action (which is just paste) and replace it with my own action (Paste, and then color syntax).
Code:
[B]//INSIDE THE CONSTRUCTOR FOR THE GUI:[/B]
//Override the paste action (Ctrl+V) with our own system of handling
//pasting. We need a custom paste action for syntax coloration.
textBox.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V,
KeyEvent.CTRL_MASK),"none");
Custom Ctrl+V action:
Code:
private void pasteActionPerformed(java.awt.event.ActionEvent evt) {
if (isIndentEditorSelected()) {
makeIndentBoxVisible();
indentEditorPane.paste();
} else {
makeTextBoxVisible();
textBox.paste();
}
[COLOR="Green"]refreshSyntaxColorationBasedOnCheckBox();[/COLOR]
}
So basically, you have to write event listeners for KeyReleased and the Ctrl+V shortcut for your textPane, then run those necessary methods.