Hm..
For the Assembler's syntax highlighting, I didn't check for Document changes at all, so I didn't need to use DocumentListener.
I concluded that there were only 3 times that a document could change:
1. Opening a file.
2. Pasting text.
3. Typing (pressing a key and then releasing it)
Cutting (Ctrl+X) also changes the document but doesn't insert new text so it's okay to ignore it.
Recoloring the syntax upon opening a file is easy because you just do that right after the user presses the Open File button or whatever.
Instead of a document listener, I used a Key Listener to listen for keypresses (which signals change of text b/c of typing):
(My JTextPane has been named textBox)
Code:
[B]//Add Listener. Put inside your GUI's constructor:[/B]
textBox.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textBoxKeyReleased(evt);
}
});
//Put this in the main body of the GUI class:
//This method will be run whenever a key is released by the user.
private void textBoxKeyReleased(java.awt.event.KeyEvent evt) {
if (useSyntaxColorsCheckBox.isSelected())
syntaxObj1.styleAsmCodeInLine(textBox,textBox.getCaretPosition());
}
Again, I used KeyReleased instead of KeyPressed because KeyPressed causes chronological issues.
Paste was different. Ctrl+V normally works as paste in all JTextPanes, but we don't want that because we need to do a paste, and then color the syntax.
So, we must override the paste action and replace it with a custom action. This requires an Action Listener, not a DocumentListener:
Code:
[B]//Remove paste action. Put inside your GUI's constructor:[/B]
textBox.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V,
KeyEvent.CTRL_MASK),"none");
//Class field declaration follows. Put in main body of GUI class.
paste = new javax.swing.JMenuItem();
[B]//Create new shortcut Ctrl+V for custom paste option. Put inside your GUI's constructor:[/B]
paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
paste.setText("Paste");
paste.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pasteActionPerformed(evt);
}
});
editMenu.add(paste);
//This method is the custom paste option.
//First it makes the text pane visible,
//then it performs a paste.
//Finally, it recolors the syntax.
private void pasteActionPerformed(java.awt.event.ActionEvent evt) {
makeTextBoxVisible();
textBox.paste();
refreshSyntaxColorationBasedOnCheckBox();
}
The paste+recolor syntax method is "connected" to the Paste button on the Edit Menu, which is also the same as pressing Ctrl+V if you disable the default Ctrl+V action for your JTextPane first.