Question

I'm making a custom textfield (drawing the text instead of using JTextField). I can type the characters in, but the backspace only clears one character. Then if I write something more, I can delete one character again. I have no idea why.

KeyListener:

class KeyController implements KeyListener {
        public void keyPressed(KeyEvent e) {
            if (!chat.getUsing()) {
                player.keyPressed(e);
            } else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                chat.keyTyped(e);
            }

            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                if (chat.getUsing()) {
                    chat.setUsing(false);
                } else {
                    chat.setUsing(true);
                }
            } 
        }

        public void keyReleased(KeyEvent e) {
            if (!chat.getUsing()) {
                player.keyReleased(e);
            }
        }

        public void keyTyped(KeyEvent e) {
            if (chat.getUsing() && e.getKeyCode() != KeyEvent.VK_BACK_SPACE) {
                chat.keyTyped(e);
            }
        }
    }

The keyTyped() method in the chat object:

public void keyTyped(KeyEvent ev) {
        if (ev.getKeyCode() != KeyEvent.VK_BACK_SPACE) {
            currentText += ev.getKeyChar();
        } else {
            if (currentText.length() > 0) {
                currentText = currentText.substring(0, currentText.length() - 1);
            }
        }
    }

And I'm drawing out the currentText string.

Was it helpful?

Solution

Try this one

 e.getKeyChar() != KeyEvent.VK_BACK_SPACE

in place of

 e.getKeyCode() != KeyEvent.VK_BACK_SPACE

in keyTyped() method.


Directly from JavaDoc of KeyEvent

The getKeyChar method always returns a valid Unicode character or CHAR_UNDEFINED. Character input is reported by KEY_TYPED events: KEY_PRESSED and KEY_RELEASED events are not necessarily associated with character input. Therefore, the result of the getKeyChar method is guaranteed to be meaningful only for KEY_TYPED events.

For key pressed and key released events, the getKeyCode method returns the event's keyCode. For key typed events, the getKeyCode method always returns VK_UNDEFINED. The getExtendedKeyCode method may also be used with many international keyboard layouts.

For more info read here about Key Event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top