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
and disable it by calling

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

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);



       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;

       private void doEnablement() {
           if (field.getText().isEmpty()) {
           } else {

       public void insertUpdate(DocumentEvent e) {

       public void removeUpdate(DocumentEvent e) {

       public void changedUpdate(DocumentEvent e) {

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(true); //OK button doesnot get enabled
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo