3
votes

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

3

3 Answers

4
votes

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.

1
votes

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);
}
});
0
votes

In your actionPerformed method, for every actionEvent checking, check whether the required fields are filled up, if so, set your button setEnabled(true). Perhaps a better answer can be provided if you can show us your code.