1

I am creating a small application. I have 2 JTextFields. When compile 2 sentence between 2 jTextFields I want to show the error word in red color in 2nd jTextFiled. I have create a small code but it is showing whole sentence as in red. (For example I have a sentence like "abcd efgh ijkl". If I re-enter the word in jTextField as "abcd egfh lkjl" I want to show only error words in red color).

My code is as follows:

private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:

       if(jTextField1.getText().trim().equals(jTextField2.getText().trim()))
{
     jTextField2.setForeground(Color.green);
}
else
{
  jTextField2.setForeground(Color.red);
}
    }
Arsaceus
  • 293
  • 2
  • 19
  • JTextArea can't do this, it only supports plain/non-mark text, it's also not capable of supporting StyledDocument, you'll have to cheat and use a JTextPane – MadProgrammer Feb 04 '16 at 03:18
  • What's showing you an error? – MadProgrammer Feb 04 '16 at 03:29
  • 1
    @MadProgrammer it is showing whole sentence as in red. I want to show the word which is typed in mistake only showing in red – user5876281 Feb 04 '16 at 03:38
  • Yes, that's what JTextFied does, see my first comment, you can't achieve what you're tying with a JTextField – MadProgrammer Feb 04 '16 at 03:40
  • @MadProgrammer I have already given the Jtextpane but still same error happening. – user5876281 Feb 04 '16 at 04:33
  • Okay, highlighting one or more characters in a `JTextPane` is not as simple as calling `setForeground`, you can either change the `AttributeSet` associated with a portion of the text or apply a highlighter. Maybe something like [this](http://stackoverflow.com/questions/26986778/compare-two-strings-and-highlight-the-mismatch-wherever-found/26987044#26987044) or maybe [this](http://stackoverflow.com/questions/15916249/colorpane-grab-strings-of-different-character-possible/15916621#15916621) – MadProgrammer Feb 04 '16 at 04:36
  • or [this](http://stackoverflow.com/questions/19399904/set-hilighting-color-in-jtextfield/19401765#19401765) or [this](http://stackoverflow.com/questions/14727548/java-change-the-document-in-documentlistener/14727657#14727657) – MadProgrammer Feb 04 '16 at 04:42
  • 2
    @MadProgrammer thank you – user5876281 Feb 04 '16 at 04:50

0 Answers0