ColdStormy ColdStormy - 1 year ago 148
Java Question

Java - Check if JTextField is empty or not

So I got know this is a popular question and already found the solution. But when I try this it doesn't work properly.

My JTextField is empty and the button isn't enabled. When I write something in my textfield the button doesn't get enabled.

So my program should check this field every second whether it's empty or not. As soon as someone writes something into the textfield the button should be enabled.^^

loginbt = new JButton("Login");
loginbt.addActionListener(new loginHandler());

if(name.getText().equals("")) {
}else {

Answer Source

For that you need to add change listener (a DocumentListener which reacts for change in the text) for your JTextField, and within actionPerformed(), you need to update the loginButton to enabled/disabled depending on the whether the JTextfield is empty or not.

Below is what I found from this thread.

yourJTextField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
  public void removeUpdate(DocumentEvent e) {
  public void insertUpdate(DocumentEvent e) {

  public void changed() {
     if (yourJTextField.getText().equals("")){
     else {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download