1

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 Answers1

2

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.

Basilio German
  • 1,801
  • 1
  • 13
  • 22
  • 1
    Well, e.getKeyCode() returns an int, and KeyEvent.VK_C is an int http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/event/KeyEvent.html#getKeyCode%28%29 – Basilio German May 22 '12 at 14:41
  • simple wrong answer why to override built-in KeyBindings shortcut by KeyListener, issue is that you can guarantee Listeners ordering, – mKorbel May 22 '12 at 15:00
  • what do you mean? have you tried using commas in your sentences? – Basilio German May 22 '12 at 15:08
  • KeyListener isn't designated to listening keyboards events for Swing JComponents, for the safest way is required to use KeyBindings, btw there are another ways how to protect SystemClipboard (ctrl + c / x) – mKorbel May 22 '12 at 16:08