Enable or disable a JButton based on JTextField content in Java

Description

The following code shows how to enable or disable a JButton based on JTextField content.

Example


import java.awt.FlowLayout;
/*w w w .  j  a  v  a2  s  .  c  o m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame("Text Field Elements");

    f.setLayout(new FlowLayout());

    JButton button = new JButton("foo");
    JTextField textfield = new JTextField(10);
    Document document;
    document = textfield.getDocument();
    document.addDocumentListener(new JButtonStateController(button));

    f.add(button);
    f.add(textfield);
    f.pack();
    f.setVisible(true);

  }


}
class JButtonStateController implements DocumentListener {
  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);
  }
}

The code above generates the following result.

Enable or disable a JButton based on JTextField content in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer