1

如何防止用户复制 JTextField 的内容?

我有以下内容,但我无法想办法同时获取多个密钥?

myTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
  char c = e.getKeyChar();
  if (!Character.isDigit(c)) {
    e.consume();
  }
}
});
4

1 回答 1

2

为此,您必须修改 KeyAdapter 以便它可以在按下键和释放键时进行注册,这样我们就可以知道两个键何时同时按下,下面的代码应该可以解决问题:

textfield.addKeyListener(new KeyAdapter() {
        boolean ctrlPressed = false;
        boolean cPressed = false;

        @Override
        public void keyPressed(KeyEvent e) {
            switch(e.getKeyCode()) {
            case KeyEvent.VK_C:
                cPressed=true;

                break;
            case KeyEvent.VK_CONTROL:
                ctrlPressed=true;
                break;
            }

            if(ctrlPressed && cPressed) {
                System.out.println("Blocked CTRl+C");
                e.consume();// Stop the event from propagating.
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            switch(e.getKeyCode()) {
            case KeyEvent.VK_C:
                cPressed=false;

                break;
            case KeyEvent.VK_CONTROL:
                ctrlPressed=false;
                break;
            }

            if(ctrlPressed && cPressed) {
                System.out.println("Blocked CTRl+C");
                e.consume();// Stop the event from propagating.
            }
        }
    });

我只是将它添加到我的一个 JTextFields 中。

于 2012-05-22T14:21:16.467 回答