Password in JTextArea

2020-04-20 08:29发布

问题:

Is there any way using JTextArea to hide the text when user types??

Kind of like password..

in JTextArea i have..

password:

in last line and whatever user types in that line shouldn't be visible.

I have tried with setForeground method to set font colour to textarea colour which makes text invisible but allows user to copy and paste.

is there any workaround or how can i achieve this??

Please help

回答1:

Here's what I was talking about in comments. Do note that this is just a quick example (might wanna store the password securely, etc.), but should get you started.

This code simply puts a DocumentFilter on the JTextArea and never allows password characters to be put into it's Document. Instead they are re-routed somewhere else. This is similar behavior to that of a console expecting sensitive input.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class CapturePassword extends JFrame {

    private JScrollPane scroll;
    private JTextArea textArea;
    private JToggleButton expectPassword;
    private StringBuilder password; // you would of course use something else

    public CapturePassword() {
        setLayout(new BorderLayout());

        password = new StringBuilder();

        textArea = new JTextArea();
        scroll = new JScrollPane(textArea);
        add(scroll);

        expectPassword = new JToggleButton("Capture password");
        add(expectPassword, BorderLayout.PAGE_END);

        expectPassword.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (expectPassword.isSelected()) {
                    capture(true);
                } else {
                    capture(false);
                    JOptionPane.showConfirmDialog(
                            CapturePassword.this, 
                            "Captured password: " + password.toString(), 
                            "Password!", JOptionPane.DEFAULT_OPTION, 
                            JOptionPane.INFORMATION_MESSAGE);
                    password.setLength(0); // reset
                }
                textArea.requestFocusInWindow();
            }
        });

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 400);
        setLocationRelativeTo(null);
    }

    private void capture(boolean start) {
        PlainDocument document = (PlainDocument)textArea.getDocument();
        DocumentFilter filter = new DocumentFilter() {

            private void doAppend(String text) {
                if (text.endsWith("\n")) {
                    expectPassword.doClick();
                } else {
                    password.append(text);
                }
            }

            @Override
            public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
                // you would have to handle multi-line pastes here also
                doAppend(text);
            }

            @Override
            public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
                // cannot remove while filtering
            }

            @Override
            public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                doAppend(text);
            }          
        };
        document.setDocumentFilter(start ? filter : null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                new CapturePassword().setVisible(true);
            }
        });
    }

}


回答2:

Use the JPasswordField class, a subclass of JTextField, provides specialized text fields for password entry.

Here's the link for reference: http://docs.oracle.com/javase/tutorial/uiswing/components/passwordfield.html



回答3:

Simply use JPasswordField a subclass of JTextField. It's very clearly and simply discussed in java doc so I avoid repeat.



回答4:

I have tried with setForeground method to set font colour to textarea colour which makes text invisible but allows user to copy and paste.

You need to use a JTextPane if you want to play with different attributes for different parts of the text.

Read the section from the Swing tutorial on Text Component Features for more information and working examples.