there is a window, there are two elements in it - a button and a text field (JTextField), how to realize that after removing characters from a field, it becomes white (before that it changes color), this should happen automatically when the field is empty

    1 answer 1

    If you need to change the color after leaving the field, hang the FocusListener and in the focusLost method check the length of the string in the field:

    JTextField field = new JTextField(); field.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { if (field.getText().isEmpty()) field.setBackground(new Color(255, 255, 255)); } }); 

    If the text will be changed programmatically:

     field.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { warn(); } public void removeUpdate(DocumentEvent e) { warn(); } public void insertUpdate(DocumentEvent e) { warn(); } public void warn() { if (field.getText().isEmpty()) field.setBackground(new Color(255, 255, 255)); } }); 
    • does not plow. It is necessary - when I press the row and press the back space key to delete characters from the field, when I delete the last character, it (the row) should turn white. ps I work through jframe, - Maxim Alexandrov