Java - Check if JTextField is empty or not

前端 未结 11 946
北恋
北恋 2020-11-27 17:44

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

相关标签:
11条回答
  • 2020-11-27 18:06

    What you need is something called Document Listener. See How to Write a Document Listener.

    0 讨论(0)
  • 2020-11-27 18:11

    Try with keyListener in your textfield

    jTextField.addKeyListener(new KeyListener() {
    
            @Override
            public void keyTyped(KeyEvent e) {
            }
    
            @Override
            public void keyPressed(KeyEvent e) {
                if (text.getText().length() >= 1) {
                    button.setEnabled(true);
                } else {
                    button.setEnabled(false);
                }
            }
    
            @Override
            public void keyReleased(KeyEvent e) {
            }
    
        });
    
    0 讨论(0)
  • 2020-11-27 18:13
    if(name.getText().hashCode() != 0){
        JOptionPane.showMessageDialog(null, "not empty");
    }
    else{
        JOptionPane.showMessageDialog(null, "empty");
    }
    
    0 讨论(0)
  • 2020-11-27 18:15

    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);
        }
    
      }
    });
    
    0 讨论(0)
  • 2020-11-27 18:16

    Well, the code that renders the button enabled/disabled:

    if(name.getText().equals("")) {
        loginbt.setEnabled(false);
    }else {
        loginbt.setEnabled(true);
    }
    

    must be written in javax.swing.event.ChangeListener and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?

    0 讨论(0)
提交回复
热议问题