Garnele007
Garnele007

Reputation: 38

Remove more than one character of a ArrayList with a Keylistener

If I remove the last character of my character ArrayList, the ArrayList is not shorter than before removing a Character. So I can not remove more characters than one.

public static ArrayList<Character>  userLineInput;

if (e.getKeyChar() == '\b') {
    if (!userLineInput.isEmpty()) {
        userLineInput.remove(userLineInput.size()-1);
        }
}

Is there a easy way to remove more than one character?

Upvotes: 0

Views: 180

Answers (1)

Mifmif
Mifmif

Reputation: 3190

it seems that you need to define something like :

while(keyIsPressed)
   if(thePressedKey == '\b'){
removeOneChar();
}

here is a quick solution that may help you :

public class RemoveChar extends KeyAdapter {
    public static ArrayList<Character> userLineInput;
    private boolean isPressed = false;
    private int pressedKey = 0;
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            while (isPressed)
                if (pressedKey == '\b')
                    removeLastChar();
        }
    });

    @Override
    public void keyPressed(KeyEvent e) {
        if (!isPressed) {
            pressedKey = e.getKeyCode();
            t.start();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (isPressed && e.getKeyCode() == pressedKey)
            isPressed = false;
    }

    public void removeLastChar() {
        userLineInput.remove(userLineInput.size() - 1);
    }
}

Upvotes: 1

Related Questions