Based on JTextField content, enable or disable a JButton : JTextField « Swing « Java Tutorial





import java.awt.BorderLayout;

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 Main() {
    JButton button = new JButton("foo");
    JTextField textField = new JTextField(10);
    Document document = textField.getDocument();
    document.addDocumentListener(new JButtonStateController(button));
  
    JFrame frame = new JFrame();
    frame.add(button,BorderLayout.WEST);
    frame.add(textField,BorderLayout.CENTER);
    frame.setSize(300,300);
    frame.setVisible(true);
  }

}
class JButtonStateController implements DocumentListener {
 JButton button;
  
  JButtonStateController(JButton button) {
     this.button = button ;
  }

  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);
  }
}










14.15.JTextField
14.15.1.Make a Text Field two columns wide
14.15.2.Sharing Data Models between two JTextFieldSharing Data Models between two JTextField
14.15.3.Adding ActionListener to JTextFieldAdding ActionListener to JTextField
14.15.4.Verifying Input During Focus TraversalVerifying Input During Focus Traversal
14.15.5.JTextField with a JScrollBar for ScrollingJTextField with a JScrollBar for Scrolling
14.15.6.Horizontal AlignmentHorizontal Alignment
14.15.7.Using JLabel Mnemonics: Interconnect a specific JLabel and JTextFieldUsing JLabel Mnemonics: Interconnect a specific JLabel and JTextField
14.15.8.To make sure that the end of the contents is visibleTo make sure that the end of the contents is visible
14.15.9.Use the write() method to write the contentsUse the write() method to write the contents
14.15.10.Drag and drop Text Demo
14.15.11.Using Actions with Text Components: JTextField
14.15.12.HighLight painter and JTextField
14.15.13.Limit JTextField input to a maximum length
14.15.14.Apply special filter to a JTextField
14.15.15.Format JTextField's text to uppercase
14.15.16.Add key listener event handler to JTextField
14.15.17.Right justified JTextfield content
14.15.18.Set the focus on a particular JTextField
14.15.19.Customizing a JTextField Look and Feel
14.15.20.Cut, paste, and copy in a JTextField
14.15.21.Aligning the Text in a JTextField Component
14.15.22.Based on JTextField content, enable or disable a JButton
14.15.23.Subclass InputVerfier
14.15.24.extends JTextField to create integer JTextField