-1

I am trying to create a xml editor which must have a content assistant. I am new in java so my code isn't working properly.

I am trying to change a text color while typing (words between '<' and '>' including '<' and '>' must be blue), my non working code:

textPane.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent arg0) {
            char key = arg0.getKeyChar();
            switch(key){
            case '<': textPane.setForeground(Color.blue); break;
            case '>': textPane.setForeground(Color.black); break;
        }
    }

Thanks

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Student22b
  • 79
  • 3
  • 13
  • 1
    "Not working properly" isn't descriptive. What is the error you are receiving? – Jimbo Aug 24 '13 at 15:07
  • Are you being sure to repaint the frame? Whatever changes you apply to the stuff in the frame do not take effect until you repaint the frame (or if the system auto refreshes the display). – gparyani Aug 24 '13 at 15:24
  • Though consider getting your hands on `Regular Expressions`. The approach you using (`KeyListeners`) won't work, if in case someone copies the content from somewhere else and paste the same on the `JTextPane`, consider using `DocumentFilter`. For more info, see [Text Component Features](http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html) :-) – nIcE cOw Aug 24 '13 at 17:06

1 Answers1

3

Your approach is not going to work. You need to work with the Document, AttributeSet and DocumentListener classes.

DocumentListener tutorial: http://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html

Try doing some reading, and come back with questions about that approach. All you're going to accomplish with your current tack is changing the text color of the entire component, not just the bits between angle brackets.

Is this part of the assignment? It seems a little involved for somebody new to programming.

Eric Stein
  • 13,209
  • 3
  • 37
  • 52