Search code examples
javaswingjtextareakeylistenerenter

Java add time to keyReleased?


I am capturing each keyPress within a JTextArea and sending it off to the chatserver to let the person on the other end know that the user is typing.

Currently I got this:

sm.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            sendMsg(sm.getText(), "message", atName);
            sm.setText(null);
        } else { // Typing
            sendMsg("", "typing", atName);
        }
    }
});

This works fine it sends sendMsg("", "typing", atName); on each keypress except for Enter.

However this is slowing down the server a bit.

How could i add a timer or something to this in order not to send exactly all keypresses?


Solution

  • You could have a flag which would indicate if the user was typing. Then you could only send one "typing" message, the first time they press a key.

    boolean isTyping = false;
    
    sm.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                sendMsg(sm.getText(), "message", atName);
                sm.setText(null);
                isTyping = false;
            } else { // Typing
                if (isTyping) {
                    if (sm.getText().length() == 0) {
                        isTyping = false;
                        // Send a message indicating the user has stopped typing
                        sendMsg("", "stopTyping", atName); //Customize the message type here, may need to adjust the server
                    }
                } else {
                    isTyping = true;
                    sendMsg("", "typing", atName);
                }
            }
        }
    });