--EDIT--
我有一个JTextField,并且我希望每次有人更改(键入或删除)JTextField 中的字符时调用一个方法(现在只是打印语句)。它背后的目的是让该方法立即检查键入的内容是否满足某些条件。感谢您的帮助,我设法写了:
public class MyDocumentListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
updateLog(e, "inserted into");
}
public void removeUpdate(DocumentEvent e) {
updateLog(e, "removed from");
}
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
}
public void updateLog(DocumentEvent e, String action) {
System.out.println("should call the method here");
}
}
JTextField 代码:
JTextField passwordField = new JTextField();
passwordField.getDocument().addDocumentListener(new MyDocumentListener());
passwordField.getDocument().putProperty("name", "Text Field");
我现在遇到的问题是我需要使用
String textFieldPassword = passwordField.getText();
但它返回NullPointerException
。我假设这是因为我添加了DocumentListener
and 应该DocumentEvent
现在正在运行。但我真的不知道该怎么做。