如何在JPasswordField中剪切/复制文本作为char数组?

时间:2013-07-17 17:36:32

标签: java swing jpasswordfield

如何使用非String API JPasswordField中的密码剪切/复制到剪贴板中。从而关闭一个黑客看到密码的窗口。

根据此链接https://stackoverflow.com/a/8885343/2534090,char数组与文本不同。

public static void main(String[] args) {
    Object pw = "Password";
    System.out.println("String: " + pw);

    pw = "Password".toCharArray();
    System.out.println("Array: " + pw);
}

打印

String: Password
Array: [C@5829428e

我想要在剪贴板中的内容是[C@5829428e,而不是Password

我尝试使用StringSelection复制剪贴板中的内容,但它的构造函数采用String,这是不可变的,不安全。

1 个答案:

答案 0 :(得分:1)

您可以使用自定义TransferHandler执行此操作。

根据Using and Creating a Data Flavor上的Swing教程中的部分,您应该能够使用char []作为写入剪贴板的对象。

然而,我无法使其工作并最终将StringBuilder写入剪贴板。我评论了代码是我试图使用char [],也许其他人可以弄清楚我做错了什么。

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.*;

public class PasswordHandler extends TransferHandler
{
//  public final static DataFlavor CHAR_ARRAY_FLAVOR = new DataFlavor(char[].class, "Char Array");
    public final static DataFlavor CHAR_ARRAY_FLAVOR = new DataFlavor(StringBuilder.class, "StringBuilder");

    @Override
    public int getSourceActions(JComponent c)
    {
        return COPY;
    }

    @Override
    public Transferable createTransferable(final JComponent c)
    {
        return new Transferable()
        {
            @Override
            public Object getTransferData(DataFlavor flavor)
            {
                JPasswordField textField = (JPasswordField)c;
//              return textField.getPassword();
                return new StringBuilder( textField.getText() );
            }

            @Override
            public DataFlavor[] getTransferDataFlavors()
            {
                DataFlavor[] flavors = new DataFlavor[1];
                flavors[0] = CHAR_ARRAY_FLAVOR;
                return flavors;
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor flavor)
            {
                return flavor.equals(CHAR_ARRAY_FLAVOR);
            }
        };
    }

    @Override
    public boolean canImport(TransferSupport support)
    {
        boolean canImport = support.isDataFlavorSupported(CHAR_ARRAY_FLAVOR);
        return canImport;
    }

    @Override
    public boolean importData(TransferSupport support)
    {
//      char[] password;
        StringBuilder password;

        try
        {
//          password = (char[])support.getTransferable().getTransferData(CHAR_ARRAY_FLAVOR);
            password = (StringBuilder)support.getTransferable().getTransferData(CHAR_ARRAY_FLAVOR);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

        JPasswordField textField = (JPasswordField)support.getComponent();
        textField.setText(password.toString());
        return true;
    }

    private static void createAndShowUI()
    {
        JPasswordField tf1 = new JPasswordField(10);
        JPasswordField tf2 = new JPasswordField(10);

        TransferHandler handler = new PasswordHandler();
        tf1.setTransferHandler( handler );
        tf2.setTransferHandler( handler );
        tf1.putClientProperty("JPasswordField.cutCopyAllowed",true);
        tf2.putClientProperty("JPasswordField.cutCopyAllowed",true);

        JFrame frame = new JFrame("Password Copy");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(tf1, BorderLayout.WEST);
        frame.add(tf2, BorderLayout.EAST);
        frame.add(new JTextField(), BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

代码从密码字段中获取整个文本。如果您只想要所选字符,则需要修改getTransferData()方法,只将选定的字符添加到StringBuilder中。