I have a requirement where I am entering input in JTextarea at run time and input should be masked. I am able to achieve this through below code snippet
if(encryptKeystroke == true) {
jTextArea.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getExtendedKeyCode() == KeyEvent.VK_BACK_SPACE) {
if(text.length() > 0)
text = text.substring(0, text.length() - 1);
}
else {
text += String.valueOf(e.getKeyChar());
}
jTextArea.setText(text.replaceAll(".", "*"));
}
public void keyReleased(KeyEvent e) {
jTextArea.setText(text.replaceAll(".", "*"));
}
});
}
Issue is when I am running this, entered character is visible for a small moment and then getting masked(like it happened in Android). I am using JTextarea because unable to achieve the scrollable & wrapstyle in Ttextfield. Any suggestion how this can be achieved ?
Don't use a KeyListener for something like this. What if the user:
A KeyListener can't handle all these special situations. Swing has better and newer API's to use.
Instead you can use a
DocumentFilter. TheDocumentFilterallows you to filter the text BEFORE it is added to theDocumentof theJTextArea.Basic example: