Reputation: 35
I have few text fields. How to enable button if user filled all text fields and disable if user delete something? I'm using Swing.
Upvotes: 1
Views: 8273
Reputation: 51333
Since swing is based on MVC you can use the model objects and listen to changes.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
JTextField textField1 = new JTextField(30);
JTextField textField2 = new JTextField(30);
JTextField textField3 = new JTextField(30);
JButton jButton = new JButton("Button");
ButtonModel model = jButton.getModel();
Document document1 = textField1.getDocument();
Document document2 = textField2.getDocument();
Document document3 = textField3.getDocument();
ButtonEnablement buttonEnablement = new ButtonEnablement(model);
buttonEnablement.addDocument(document1);
buttonEnablement.addDocument(document2);
buttonEnablement.addDocument(document3);
contentPane.add(textField1);
contentPane.add(textField2);
contentPane.add(textField3);
contentPane.add(jButton);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Whenever one Document
changes the ButtonEnablement
will take a look at all Document
s and enable the ButtonModel
.
public class ButtonEnablement implements DocumentListener {
private ButtonModel buttonModel;
private List<Document> documents = new ArrayList<Document>();
public ButtonEnablement(ButtonModel buttonModel) {
this.buttonModel = buttonModel;
}
public void addDocument(Document document) {
document.addDocumentListener(this);
this.documents.add(document);
documentChanged();
}
public void documentChanged() {
boolean buttonEnabled = false;
for (Document document : documents) {
if (document.getLength() > 0) {
buttonEnabled = true;
break;
}
}
buttonModel.setEnabled(buttonEnabled);
}
@Override
public void insertUpdate(DocumentEvent e) {
documentChanged();
}
@Override
public void removeUpdate(DocumentEvent e) {
documentChanged();
}
@Override
public void changedUpdate(DocumentEvent e) {
documentChanged();
}
}
The advantage of using a ButtonModel
and Document
instead of a JButton
and JTextField
is that you can easily change the concrete implementations and you don't have to worry on how your ui components get updated, because they get updated automatically when their model changes.
Upvotes: 1
Reputation: 412
You could set an event listener to see when textfields change. Then disable the button if an fields are empty:
field1.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) { //watch for key strokes
if(field1.getText().length() == 0 || field2.getText().length() == 0)
button.setEnabled(false);
else
{
Button.setEnabled(true);
}
}
});
The strategy here is:
Upvotes: 0