How to enable cut and copy in JPasswordField?

Identifying password image
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()
    private void createAndShowGUI()
        setTitle("Disable Cut Copy");
        jt=new JPasswordField(20){
            public void paste(){}
        // Put client property
        // true=allow cut/copy
        // false=disallow (default)
    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.

Posted by at on

Tags: Swing Hacks,