Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advice needed with disabling a JButton until required fields have been filled in - Java

I am making a courier program in which the user can create a new account. I want to have a next button that the user cannot press until the text fields have been filled in.

So a blank Name Field and Surname field would mean the next button cannot be pressed but if the fields have been filled in, the next button can be pressed

like image 255
fez Avatar asked Dec 27 '25 16:12

fez


2 Answers

Add a KeyListener like this to your fields:

nameField.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent e) {
            super.keyReleased(e);
            if(nameField.getText().length() > 0 && surNameField.getText().length() > 0)
                nextButton.setEnabled(true);
            else
                nextButton.setEnabled(false);
        }
    });

This will check if the two fields are not empty, every time a key has been pressed in the field. If the condition is true, the next button will be enabled.

like image 91
CleanUp Avatar answered Dec 31 '25 15:12

CleanUp


In simple term, try something like.

String text = textField.getText();
if (text.length()>0)
   button.setEnabled(true);
 ...

If you want to have the button enable on the fly then its a bit more complicated

EDIT :

complicated case:

Document textFieldDoc = myTextField.getDocument();
textFieldDoc.addDocumentListener(new DocumentListener() {
 void changedUpdate(DocumentEvent e) {
   updated(e);
}
void insertUpdate(DocumentEvent e) {
   updated(e);
}
void removeUpdate(DocumentEvent e) {
   updated(e);
}
private void updated(DocumentEvent e) {
   boolean enable = e.getDocument().getLength() > 0;
   myButton.setEnabled(enable);
}
});
like image 39
mu_sa Avatar answered Dec 31 '25 13:12

mu_sa