Search code examples
javaswingbackgroundjtextfield

Updating background color of JTextField automatically


well i made a JTextField and i want it's background to be red when there are no characters in it, and once a character is written to be automatically changed to green.

i tried this code

textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN);

but it doesn't automatically update it.

thanks


Solution

  • you should add documentListener

    textfield.getDocument().addDocumentListener(this);
    
    @Override
        public void insertUpdate(DocumentEvent e) 
        {
            textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN);
        }
    
        @Override
        public void removeUpdate(DocumentEvent e) 
        {
            textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN);
        }
    
        @Override
        public void changedUpdate(DocumentEvent e) 
        {
            textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN);    
        }
    

    Also try setting the opaque property of the Textfield.

    textField1.setOpaque(True)