Java查漏补缺3-Swing中的文本绑定监听
在做简单的Swing开发中,会经常遇到这样的情况,需啊监听文本框的内容的变化。比如一个最简单的例子就是如果登陆框中用户名和密码都不为空的时候,登陆按钮才被激活。
在查看事件的时候,很多人第一眼看到的就是InputMethod下面的caretPositionChanged和inputMethodTextChanged。无论从文档还是从函数名字来看,这两个函数似乎都是我们所需要实现的方法。可惜当你填满了里面的内容,DEBUG的时候,会发现无论如何你改变你的输入框的内容,根本都不会触发这两个事件。在Sun的论坛上,有个人回了这样一句话来解决这个问题:“A component will only receive input method events from input methods if it also overrides getInputMethodRequests to return an InputMethodRequests instance.”
不愿意为这个问题多纠结,给出解决方案就是使用DocumentListener。这个接口提供了三个方法来侦听所绑定的文本的内容。对于我们需要的监听对象,直接添加这个侦听器,并实行其中的方法即可。
Document doc1 = jTextFieldId.getDocument();
doc1.addDocumentListener(new DocumentListener() {
String name;
String pwd;
public void insertUpdate(DocumentEvent e) {
name = jTextFieldId.getText();
pwd = new String(jPasswordFieldPassword.getPassword());
if(!name.equals("") && !pwd.equals("")){
jButtonSignIn.setEnabled(true);
} else {
jButtonSignIn.setEnabled(false);
}
}
public void removeUpdate(DocumentEvent e) {
name = jTextFieldId.getText();
pwd = new String(jPasswordFieldPassword.getPassword());
if(!name.equals("") && !pwd.equals("")){
jButtonSignIn.setEnabled(true);
} else {
jButtonSignIn.setEnabled(false);
}
}
public void changedUpdate(DocumentEvent e) {
}
});
This entry was posted on Sunday, June 28th, 2009 at 3:01 pm and is filed under J2SE . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.



