How to create Swing Button, Enabled and Disabled





1) . Create simple interface using NetBeans as follow.



 2) . Rename Button as btnOk and TextField as txtSomeText .


 3) . In constructor add below code for disable the button when start of program.

                //Dissable Button at startup
          btnOK.setEnabled(false);


 4) . In TextField's KeyRelease Event add below code for check for not empty textfield and enable button and when it comes empty disable the button.

                 // Enable Button when there has some text in Text field
        if(!txtSomeText.getText().equals("")){
            btnOK.setEnabled(true);
        }else{
            btnOK.setEnabled(false);
        }


 5) . In the Button's ActionPerformed Event add below code for show a message box for sample thing to do on button.

             //You can do what you want in here
        JOptionPane.showMessageDialog(this, "Button Enabled.\n You entered "+txtSomeText.getText()+" .");


 6) . Run the interface and it may look like this.


 7) . Get download total NetBeans Project from below.

NetBeans Project - 


***************************************************

BEST OF LUCK !

***************************************************


If you have any Java Problems add as comment in here.

No comments:

Post a Comment