【问题标题】:What event to use when pasting something in a JTextField?在 JTextField 中粘贴内容时使用什么事件?
【发布时间】:2013-09-27 10:35:45
【问题描述】:

我有一个JTextField。当我在JTextField 中粘贴一些内容时,我希望执行一个事件。我需要什么活动来解决我的问题?

【问题讨论】:

    标签: java swing jtextfield


    【解决方案1】:

    KeyListener 不起作用如果您粘贴在文本中,这就是为什么您应该使用DocumentListener

    检查链接,它解释得很好,这里有一些开始:

    private DocumentListener myListener = new DocumentListener() {
    
        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
            //...
        }
        ...
        ...
    }
    

    【讨论】:

    • 你是对的,应该是MyDocumentListenerinsertUpdate
    • 当我使用条形码阅读器扫描条形码时,它是否被视为粘贴?
    【解决方案2】:

    同意 Maroun Maroun 关于KeyListener

    在粘贴时使用DocumentListener with insertUpdate 方法,比如

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

    添加监听器:

    textField.getDocument().addDocumentListener(documentListener);
    

    【讨论】:

      猜你喜欢
      • 2012-01-19
      • 1970-01-01
      • 2012-01-23
      • 2010-09-23
      • 2012-07-21
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多