I'm created a jtextpane with two different styles: one for the numbers (pink foreground) and a default style for the rest (black foreground). I have added a keylistener (I use the KeyReleased function) at the jtextpane in order to handle the new pressed character, but I have a problem during writing. The scenario is the following:
- The text is: hello 123
- And the 'hello' text is black and the number '123' is pink.
- Now the caret is between '1' and '2', I press 'a' and occurring something strange.
- The character 'a' becomes pink and then black.
Why does it become black for a short time?
I handle the KeyReleased in this way:
- I set all the text with the default style (the clean phase)
- I will change the foreground in pink for only numbers
This is the example:
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
public class Example extends JFrame {
JTextPane pn = new JTextPane();
public Example() {
addDefaultStyle(pn);
addNumberStyle(pn);
pn.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent arg0) {
String text = pn.getText();
pn.getStyledDocument().setCharacterAttributes(0, text.length(), pn.getStyle("default"), true);
StringTokenizer ts = new StringTokenizer(text, " ");
while(ts.hasMoreTokens()){
String token = ts.nextToken();
try{
Integer.parseInt(token);
pn.getStyledDocument().setCharacterAttributes(text.indexOf(token), token.length(), pn.getStyle("numbers"), true);
}catch(Exception e){
pn.getStyledDocument().setCharacterAttributes(text.indexOf(token), token.length(), pn.getStyle("default"), true);
}
}
}
});
getContentPane().add(pn);
setSize(400, 400);
setLocationRelativeTo(null);
setVisible(true);
}
private void addDefaultStyle(JTextPane pn){
Style style = pn.addStyle("default", null);
pn.setForeground(Color.blue);
pn.setBackground(Color.WHITE);
StyleConstants.setForeground(style, pn.getForeground());
StyleConstants.setBackground(style, pn.getBackground());
StyleConstants.setBold(style, false);
}
private void addNumberStyle(JTextPane pn){
Style style = pn.addStyle("numbers", null);
StyleConstants.setForeground(style, Color.PINK);
StyleConstants.setBackground(style, Color.WHITE);
StyleConstants.setBold(style, true);
}
public static void main(String args []){
new Example();
}
}