0

I'm very new at coding Java and Netbeans. So basically, I have a "save" button and three text fields, I want to enable the Button when these three text fields are edited and disable the button when one of them is empty. Also I'm wondering where I should put my codes. Since it's Netbeans I'm only familiar with ActionPerformed methods, there you can set an action when a button is pressed.

If you can keep it simple it would be appreciated!

public project() {

    initComponents();
    //Here I want the window to appear in the middle of the screen
    setLocationRelativeTo(null);

    if(txfField1.getText().equals("")){
        btnSave.setEnabled(false); 
    }
    else {
        btnSave.setEnabled(true);
    }


}

I tried with this code on only one of the three text fields and It does not work, the button is always enabled. The button is initially disabled. Additionally I have also tried to put my code below this method:

public class project extends javax.swing.JFrame {

skyever
  • 23
  • 1
  • 6
  • Please let us know what have you tried, and where exactly you are stuck. No one here will provide you with source code, unless you show some of you own. Please refer to this answer for starters, http://stackoverflow.com/questions/1625855/how-to-disable-javax-swing-jbutton-in-java – Shrikant Havale Jan 18 '16 at 16:15
  • Also please improve the formatting of your question – user3743222 Jan 18 '16 at 16:34

2 Answers2

0

You can add it in onblur() method of those text boxes.

If it can, you can add a validation with an error message on click of save button, which might be more meaningful.

Sathyan
  • 76
  • 2
  • 8
0

You can use event handlers to change the state of the button. For example, if you have one text field and you want to change the state of the button depending on the data inside the text field, you could use something like

if (!jTextField1.getText().equals("")) {
            jButton1.setEnabled(true);
} else {
            jButton1.setEnabled(false);
}

and the event handler you can use

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) { 

You can generate this automatically in Netbeans by going to the event tab when you have clicked on a component in the design view.

It seems in your example you have the right idea, however you need to update the button using events such as key pressing, key releasing etc

enter image description here

kbz
  • 984
  • 2
  • 12
  • 30
  • Hey! Should I right-click on the JButton or the text fields to find the event tab? What is the next step after it? Sorry, but I'm very new to programming in general. – skyever Jan 18 '16 at 16:31
  • @skyever I've updated my post. It's in the properties tab -> Events – kbz Jan 18 '16 at 16:43