Search code examples
javaswingactionlistenerjcomboboxjtextfield

How to enable label and textfield when combo box item selected


I created one combobox with two item as " Active " and " Droped " then i take one label with jtextfield and write code for enable and disable of label and jtextfield in the jcomboobx action event so code is working but here one problem which is that label and jtextfield initially not disabled...when i select item " Droped " then select item " Active " after its going disabled otherwise initially when run jframe, label and jtextfield enabled so i want how to jlablel and Jtextfield enable when jcombobx select item " Droped " only

source code:

private void wtdlActionPerformed(java.awt.event.ActionEvent evt) {                                     

        txt_reason.setEnabled(false); //txt_reason is jTextField
        lab.setEnabled(false); //lab is jLabel

        if(wtdl.getSelectedItem().equals("Active")) //wtdl is jConobbox
        {
        txt_reason.setEnabled(false);
        lab.setEnabled(false);
        }
      else if(wtdl.getSelectedItem().equals("Droped"))
        {
        txt_reason.setEnabled(true); 
        lab.setEnabled(true);
        }
    }

check snapshot:

enter image description here


Solution

  • Simply create a method updateState() as following:

    protected void updateState() {
        boolean enabled = wtdl.getSelectedItem().equals("Droped");
        txt_reason.setEnabled(enabled ); 
        lab.setEnabled(enabled );
    }
    

    and call it after you have initialized your components and in your actionPerformed()