Search code examples
javajtextfield

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


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

Solution

  • 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.