如果删除字符ArrayList的最后一个字符,则ArrayList不短于删除字符之前的长度。因此,我不能删除多个字符。

public static ArrayList<Character>  userLineInput;

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


有一种简单的方法可以删除多个字符吗?

最佳答案

似乎您需要定义如下内容:

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


这是一个可以帮助您的快速解决方案:

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);
    }
}

09-10 21:56