I have 4 jTextFields that I save the input to a file once a submit button is pressed. I want to be able to keep the submit button disabled until each field is at least not n
A simple runnable demo:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class ButtonDemo extends JFrame implements DocumentListener {
/**
*
*/
private static final long serialVersionUID = -68704905659973315L;
private JPanel panel = null;
private JTextField field1 = null;
private JTextField field2 = null;
private JButton btn = null;
private List textFields = null;
public static void main(String[] args) {
new ButtonDemo();
}
private ButtonDemo() {
this.panel = new JPanel();
this.field1 = new JTextField("JTextField_1");
this.field2 = new JTextField("JTextField_2");
this.field1.getDocument().addDocumentListener(this);
this.field2.getDocument().addDocumentListener(this);
this.textFields = new Vector<>();
this.textFields.add(field1);
this.textFields.add(field2);
this.btn = new JButton("Tests-Button");
this.panel.setLayout(new FlowLayout());
this.panel.add(field1);
this.panel.add(field2);
this.panel.add(btn);
this.add(panel);
this.setPreferredSize(new Dimension(200, 200));
this.pack();
this.setVisible(true);
}
@Override
public void insertUpdate(DocumentEvent e) {
updateButtonEnabledStatus(btn, textFields);
}
@Override
public void removeUpdate(DocumentEvent e) {
updateButtonEnabledStatus(btn, textFields);
}
@Override
public void changedUpdate(DocumentEvent e) {
updateButtonEnabledStatus(btn, textFields);
}
private void updateButtonEnabledStatus(JButton btn, List fields) {
boolean enabled = true;
for (JTextField field : fields) {
if (field.getText().length() == 0) {
enabled = false;
break;
}
}
btn.setEnabled(enabled);
}
}