¿Cómo habilitar un botón cuando un JTextField tenga información?

Soy principiante, estoy creando un programa en eclipse y quiero que se habilite un JButton cuando un JTextField tenga información ¿cómo lo puedo hacer?

1 Respuesta

Respuesta

Si, exactamente con keyreleased. Cuando el texto este en blanco ( length es 0 ) entonces el botón esta deshabilitado:

public void keyReleased( KeyEvent e ) {
    boton.setEnabled(
        text.getText().length() != 0
    );
}

import javax.swing.*;
import java.awt.event.*;
class DemoEvent {
    static JButton boton;
    static JTextField text;
    public static void main( String ... args ) {
      new JFrame(){{
        add( new JPanel(){{
          add(( text = new JTextField(5){{
            addKeyListener( new KeyAdapter() {
              public void keyReleased( KeyEvent e ) { // <-- Este es el importante  
                boton.setEnabled(
                  text.getText().length() != 0
                );
              }
            });
          }}));
          add(( boton = new JButton("Click"){{
            setEnabled( false );
          }}));
        }});
        pack();
        setLocationRelativeTo( null );
        setVisible( true );
      }};
    }    
}

¡Gracias! 

Muchas Gracias!!!!!!

=)

Te recuerdo que si la respuesta te fue útil, tienes valorarla y cerrarla ... recuerda que tienes varias valoraciones (espero la mejor a mi colaboración =P je je )

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas