Java - 检查JTextField是否为空 [英] Java - Check if JTextField is empty or not

查看:244
本文介绍了Java - 检查JTextField是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道这是一个很受欢迎的问题,已经找到了解决方案。但是当我尝试这个时它不能正常工作。

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

我的JTextField是空的并且没有启用按钮。当我在文本字段中写东西时,按钮不会启用。

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);
    }


推荐答案

为此您需要添加更改 JTextField 的侦听器( DocumentListener ,它会对文本中的更改作出反应),并在 actionPerformed(),您需要将 loginButton 更新为启用/禁用,具体取决于 JTextfield 是空的还是没有。

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.

以下是我从中找到的内容线程

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);
    }

  }
});

这篇关于Java - 检查JTextField是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆