V
V
vapi2018-03-24 21:38:57
Java
vapi, 2018-03-24 21:38:57

How to add a KeyListener listener in a button and how to correctly implement the KeyPressed method?

there is a small desktop application like a chat. JTextField message input field and JButton button. How can I make it so that when I press enter, the message entered in the JTextField is sent.
Tried like this, but didn't work:

JButton sendboutton = new JButton("Send message");
        sendboutton.addKeyListener(new ButtonListener());

public class ButtonListener implements KeyListener {
        @Override
        public void keyPressed(KeyEvent e) {

            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                try {
                    write.println(outgoind.getText());
                    write.flush();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                outgoind.setText("");
            }
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }
        @Override
        public void keyReleased(KeyEvent e) {
        }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question