Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());     add(loginbt);      if(name.getText().equals("")) {         loginbt.setEnabled(false);     }else {         loginbt.setEnabled(true);     } 
like image 942
ColdStormy Avatar asked Jun 16 '13 10:06

ColdStormy


People also ask

How to check if textField is empty or not?

Since we created an instance of the TextField class named text, we take text and get its value and use the isEmpty() function to see whether it is empty or not. And this is all that is required to check whether a text field is empty or not in a JavaFX application.

How to check if a field is empty in Java?

Java String isEmpty() Method The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.

How do I check if a textField is empty Python?

Using len() method We will be calculating the length of the string with the help of len() in python. Then, we will check if the string's length is equal to 0, then the string is empty; otherwise, not.

Is JTextField a class?

JTextField is a part of javax. swing package. The class JTextField is a component that allows editing of a single line of text.


1 Answers

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) {     changed();   }   public void removeUpdate(DocumentEvent e) {     changed();   }   public void insertUpdate(DocumentEvent e) {     changed();   }    public void changed() {      if (yourJTextField.getText().equals("")){        loginButton.setEnabled(false);      }      else {        loginButton.setEnabled(true);     }    } }); 
like image 159
sanbhat Avatar answered Sep 17 '22 19:09

sanbhat