JTextArea用户键入时有什么方法可以用来隐藏文本?
JTextArea
有点像密码
在JTextArea我有..
密码:
在最后一行中,该行中的任何用户类型都不应该可见。
我尝试使用setForeground将字体颜色设置为textarea颜色的方法,该颜色使文本不可见,但允许用户复制和粘贴。
setForeground
有没有解决方法,或者我该如何实现?
请帮忙
这就是我在评论中谈论的内容。请注意,这只是一个简单的示例(可能想安全地存储密码等),但是应该可以帮助您入门。
这段代码只是在DocumentFilter上放了一个,JTextArea并且永远不允许在其中添加密码字符Document。而是将它们重新路由到其他地方。这类似于期望敏感输入的控制台的行为。
DocumentFilter
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); } }); } }