How can i prevent CTRL+C on a JTextField in java?

可紊 提交于 2019-12-24 10:47:27

问题


How can i prevent a user from copying the contents of a JTextField?

i have the following but i cannot figure a way to get multiple keys at the same time?

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

回答1:


For this, you will have to modify your KeyAdapter so that it can register when a key was pressed and when it was released, so that we may know when both keys were pressed simultaneously, the following code should do the trick:

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

i was just adding this to one of my JTextFields.



来源:https://stackoverflow.com/questions/10703951/how-can-i-prevent-ctrlc-on-a-jtextfield-in-java

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