Based on JTextField content, enable or disable a JButtonTag(s): Swing
About cookies on this site
We use cookies to collect and analyze information on site performance and usage,
to provide social media features and to enhance and customize content and advertisements.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
public class DemoJButtonDisabled extends JApplet {
JButton button;
JTextField textfield;
Document document;
public void init() {
getContentPane().setLayout(new FlowLayout());
textfield = new JTextField(10);
getContentPane().add(textfield);
button = new JButton("foo");
getContentPane().add(button);
button.setEnabled(false);
document = textfield.getDocument();
document.addDocumentListener
(new JButtonStateController(button));
}
}
class JButtonStateController implements DocumentListener {
private JButton button;
JButtonStateController(JButton b) {
button = b;
}
public void changedUpdate(DocumentEvent e) {
disableIfEmpty(e);
}
public void insertUpdate(DocumentEvent e){
disableIfEmpty(e);
}
public void removeUpdate(DocumentEvent e){
disableIfEmpty(e);
}
public void disableIfEmpty(DocumentEvent e) {
button.setEnabled(e.getDocument().getLength() > 0);
}
}