What event to use when pasting something in a JTextField?

一曲冷凌霜 提交于 2019-12-13 01:39:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!