问题
I have a JTextField
. I want an event to execute when I paste something inside the JTextField
. What event do I need to solve my problem?
回答1:
KeyListener doesn't work if you paste in text, that's why you should use DocumentListener.
Check the link, it explains it very good, here's something to begin with:
private DocumentListener myListener = new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent documentEvent) {
//...
}
...
...
}
回答2:
Agree with Maroun Maroun about KeyListener
On paste use DocumentListener with insertUpdate
method, like
private class MyDocumentListener implements DocumentListener {
public void changedUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
Document document = e.getDocument();
try {
String s = document.getText(0, document.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
return;
}
}
public void removeUpdate(DocumentEvent e) {
}
}
To add listener:
textField.getDocument().addDocumentListener(documentListener);
来源:https://stackoverflow.com/questions/18943870/what-event-to-use-when-pasting-something-in-a-jtextfield