这就是我在评论中谈论的内容。请注意,这只是一个简单的示例(可能想安全地存储密码等),但是应该可以帮助您入门。
这段代码只是在
documentFilter上放了一个,
Jtextarea并且永远不允许在其中添加密码字符
document。而是将它们重新路由到其他地方。这类似于期望敏感输入的控制台的行为。
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); } }); }}


