javastringcharjpasswordfield

Deleting Last Character From a String in Java


I'm writing a java code which gives an error when typing more than 10 characters in a PasswordField and cannot type from there on. I tried deleting the last character from the PasswordField on a KeyPressed event but instead of deleting the last character, it deletes the character before it and replace it with the last character.Here goes my code.

private void passFieldKeyTyped(java.awt.event.KeyEvent evt) {

String pw1 = new String(passField.getPassword());
    
    if(passField.getPassword().length==10){

        try{

          StringBuffer bf = new StringBuffer(pw1);
           bf.deleteCharAt(10);
          String pw2 = new String(bf);    
           passField.setText(pw2);
                             
          JOptionPane.showMessageDialog(this, "<html><h4>Password Must Not Contain More Than 10 Characters !</h4></html>", "Error !", JOptionPane.ERROR_MESSAGE);

           }

        catch(Exception e){
            
           JOptionPane.showMessageDialog(this, e.getMessage());
        }

    }

I'm still a newbie for programming. I hope someone can help me with this. Thanks !


Solution

  • I guess you are trying to delete a char from the String.

    You can use the StringBuilder class here to delete a character at your specified position. First convert your String to StringBuilder -

    StringBuilder sb = new StringBuilder(inputString);
    

    Then you can use the built in method deleteCharAt() to delete the char at your desired position like this -

    sb.deleteCharAt(10);
    

    Hope this may help you.