如何在java中的JTextField上阻止CTRL + C?

时间:2012-05-22 14:18:56

标签: java jtextfield

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

我有以下但我无法想办法同时获得多个密钥?

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

1 个答案:

答案 0 :(得分:2)

为此,您必须修改KeyAdapter,以便在按下按键和释放按键时可以注册,以便我们可以知道何时同时按下两个按键,以下代码应该可以解决问题: / p>

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中。