Apache NetBeans
Apache NetBeans
Latest release

Apache NetBeans 23

Download

How can I control when the OK button is enabled?

The NetBeans Dialogs API makes it easy to create consistent dialogs that behave as users would expect. But since you don’t directly create the OK button, it may not be obvious how you can enable it or disable it.

You can enable the OK button by calling <pre>setValid(true)</pre> and disable it by calling <pre>setValid(false)</pre>

When using DialogDescriptors some additional steps need to be taken. Its OK button cannot be enabled/diabled after it has been displyed via a DialogDisplyer. The following is a sample code :

1.  Create a new Action in one of your modules using the wizard in the
NetBeans IDE


[start=2]
.  Replace the code generated inside that ActionListener with this code below:

   public void actionPerformed(ActionEvent e) {
       MyForm form = new MyForm();

       DialogDescriptor desc = new DialogDescriptor(form,

         "Hello", true, DialogDescriptor.OK_CANCEL_OPTION,
          DialogDescriptor.OK_OPTION, null);

       desc.setValid(false);

       form.setDialogDescriptor(desc);

       DialogDisplayer.getDefault().notify(desc); // displays the dialog
   }


   static class MyForm extends JPanel implements DocumentListener {

       private JTextField field;
       private DialogDescriptor desc;

       MyForm() {
           super(new BorderLayout());
           field = new JTextField();
           add(new JLabel("Type Something Here"), BorderLayout.NORTH);
           add(field, BorderLayout.SOUTH);
       }

       void setDialogDescriptor(DialogDescriptor desc) {
           this.desc = desc;
           field.getDocument().addDocumentListener(this);
       }

       private void doEnablement() {
           if (field.getText().isEmpty()) {
               desc.setValid(false);
           } else {
               desc.setValid(true);
           }
       }

       @Override
       public void insertUpdate(DocumentEvent e) {
           doEnablement();
       }

       @Override
       public void removeUpdate(DocumentEvent e) {
           doEnablement();
       }

       @Override
       public void changedUpdate(DocumentEvent e) {
           doEnablement();
       }
   }


[start=3]
.  Run your application and invoke the new action you added

Here the OK button in the dialog is initially disabled, but becomes enabled when some characters are typed. Removing all characters will disable it again.

One noteworthy point is that the following alternative fails to enable the OK button and hence the given solution is the appropriate one.

desc.setValid(false);
DialogDisplayer.getDefault().notify(desc);
desc.setValid(true); //OK button doesnot get enabled