Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do enable cut, copy in JPasswordField?

I noticed that i was unable to cut and copy in JPasswordField? Now how to copy/cut the selected part of the password to clipboard? Are there any methods to do this?

like image 982
JavaTechnical Avatar asked Jul 17 '13 17:07

JavaTechnical


People also ask

Which method is used to change the default character of JPasswordField?

The argument passed into the JPasswordField constructor indicates the preferred size of the field, which is at least 10 columns wide in this case. By default a password field displays a dot for each character typed. If you want to change the echo character, call the setEchoChar method.

What is J password field in Java?

JPasswordField is a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters. You can find further information and examples in How to Use Text Fields, a section in The Java Tutorial.


1 Answers

Simple, use this method

JPasswordField jt=new JPasswordField(20);

            // Put client property
            jt.putClientProperty("JPasswordField.cutCopyAllowed",true);

            add(jt);

By default, the password in the JPasswordField is not allowed to be cut/copied. All you need to do is to enable them.

As per the comment on disabling paste i didn't find a property, but i have achieved using this, (i dont recommend this way)

jt.getActionMap().put("a",null);
        jt.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ctrl V"),"a");

Another way, is to do override the paste() (i recommend this way) while declaring

JPasswordField jt=new JPasswordField(20){
  public void paste(){}
};

Update: I misunderstood the comment. But the above does disabling paste. However to disable any one of the copy/cut/paste, it is better if the required method that is to be disabled is overrided with no implementation in it.

If there is a much better way, i would love to hear.

like image 68
JavaTechnical Avatar answered Sep 21 '22 23:09

JavaTechnical