By default the
JPasswordField
does not allow cut and copy of the password. However, we can do it with this very simple hack which is no more than a single statement. Here is the full code on how to enable cut and copy in JPasswordField. import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import java.awt.datatransfer.*;
class EnableCutCopy extends JFrame
{
JPasswordField jt;
public EnableCutCopy()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("Disable Cut Copy");
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jt=new JPasswordField(20){
public void paste(){}
};
// Put client property
// true=allow cut/copy
// false=disallow (default)
jt.putClientProperty("JPasswordField.cutCopyAllowed",true);
add(jt);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new EnableCutCopy();
}
});
}
}
The putClientProperty()
method takes two parameters which is key, value pair respectively. There are a lot of properties but the one that does the thing is JPasswordField.cutCopyAllowed
key and the value is boolean
indicating allowed/not allowed.