Apache NetBeans Wiki Index

Note: These pages are being reviewed.

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

.  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) {

.  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

Apache Migration Information

The content in this page was kindly donated by Oracle Corp. to the Apache Software Foundation.

This page was exported from http://wiki.netbeans.org/DevFaqDialogControlOKButton , that was last modified by NetBeans user Darrshan on 2010-06-15T05:06:37Z.

NOTE: This document was automatically converted to the AsciiDoc format on 2018-02-07, and needs to be reviewed.