What event to use when pasting something in a JTextField?

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?

Upvotes: 2

Views: 3762

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

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

Upvotes: 5

Maroun
Maroun

Reputation: 95958

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) {
        //...
    }
    ...
    ...
}

Upvotes: 4

Related Questions