Disabling 'paste' in a jTextfield
Asked Answered
P

5

5

I have an app that is written in Swing, awt. I want to prevent users from pasting values into the textfields. is there any way to do this without using action listeners?

Prolegomenon answered 25/11, 2008 at 8:18 Comment(0)
M
23

You can just call setTransferHandler with a null parameter like this:

textComponent.setTransferHandler(null);

This will disable all copy/paste actions on the field.

Marginal answered 20/9, 2011 at 20:9 Comment(1)
Thanks, in my case I need to enable the paste of an image file or print screen.Lorentz
B
5

The best way is to remove action associated with CTRL+V keystroke in components ActionMap.

Boutin answered 25/11, 2008 at 11:8 Comment(0)
V
2

The simplest way it to say: textComponent.setEditable(false);

This disables cut & paste, but copy is still enabled.

Villiers answered 26/2, 2010 at 17:36 Comment(3)
True story, I have a text component where isEditable() returns false, but TransferAction still lets you paste into it. Pressing Ctrl-V is disabled, but if you have a Paste action in the main menu which is hooked up to the relevant component's transfer action, people will still be able to paste.Tinstone
@Trejkaz hmm .. haven't seen such misbehaviour since ages (early swing versions did), and can't reproduce it right now.Salzburg
Might have been fixed in the past few months.Tinstone
S
1
public class PastlessJTextField extends JTextField {

        public PastlessJTextField() {
            super();
        }
        public PastlessJTextField( int columns ){
            super( columns );
        }

        @Override
        public void paste() {
            // do nothing
        }


    }
Slurp answered 7/6, 2017 at 17:49 Comment(0)
C
0

You may be able to override the paste() method in JTextComponent.

Chance answered 25/11, 2008 at 8:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.