Call method when the Enter key is pressed

2

How to call the Send Message method when the Enter key was pressed?

Code

@Override
public void keyPressed(KeyEvent e) {
    String messageSent = "User: " + writingTextField.getText();
    if(e.getKeyCode() == KeyEvent.VK_ENTER){

        writingTextField.setText("");

        readingTextArea.setText(readingTextArea.getText() + messageSent + "\n");
    }
}
    
asked by anonymous 04.11.2015 / 17:23

1 answer

5

You can add the direct listener to the JTextField at the time it is created.

Below this code:

writingTextField = new JTextField();

Create the listener like this:

writingTextField.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent arg0) {
        if(arg0.getKeyCode() == KeyEvent.VK_ENTER) {
            System.out.println("Apertou ENTER");
        }
    }
});

This code associates a listener with writingTextField , and when a key is pressed it will enter the method in question. In the above example it just checks if it is an ENTER and prints an informational message.

If you need your ENTER to be detected regardless of where your cursor is positioned, see the solution to this question: Trigger button by shortcut key in Java .

    
04.11.2015 / 17:43