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
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.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With