Enabling a component depending on the text entered in a JTextField

Add a document listener to the JTextField and listen to the characters that are inserted and removed.

Main.java:

import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements DocumentListener
{
   private JTextField tf; 
   private JButton button;
 
   public Main() {           
      getContentPane().setLayout(new BorderLayout());
      JPanel northPanel = new JPanel(new GridLayout(1, 2));
      northPanel.add(new JLabel("Enter an integer: "));
      tf = new JTextField();
      northPanel.add(tf);
      getContentPane().add(BorderLayout.NORTH, northPanel);
      button = new JButton("OK"); 
      getContentPane().add(BorderLayout.SOUTH, button);
      // Add a document listener to the textfield
      Document document = tf.getDocument();
      document.addDocumentListener(this);
 
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.exit(1);
         }
      });
      button.setEnabled(false);
 
      pack();
   }
 
   public void insertUpdate(DocumentEvent evt) {
      String s = tf.getText();
 
      try {
         int v = Integer.parseInt(s);
         button.setEnabled(true);
      }
      catch(NumberFormatException e) {
         button.setEnabled(false);
      }
   }
 
   public void removeUpdate(DocumentEvent evt) {
      if (tf.getText().length() == 0) {
         button.setEnabled(false);
      }
      else {
         insertUpdate(evt);
      }
   }
 
   public void changedUpdate(DocumentEvent evt) {
   }
 
   public static void main(String args[]) {
      Main main = new Main();
      main.setVisible(true);
   }
}