Call method when Enter key is pressed

Asked

Viewed 1,208 times

2

How to call send message method when key Enter was pressured?

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");
    }
}
  • 1
  • I’ve seen all these sites, the problem is that I have to do by keypressed and not by action

  • Which component are you adding keypressed? I saw no problems in the code. Add the text component you want enter to work.

  • tried to verify the value of e.getKeyCode() ?

  • It is possible that he should not even be entering the event. Perhaps the most appropriate would be to put the Reader in your Textbox, and not in the form.

  • enter is not working at all. When I type into Jtextfield a text click on enter and it doesn’t work, but with mouse it works

  • As @Math said, the listerner should be assigned to Jtextfield. Post the rest of the code for easy analysis.

  • I’ve posted, but it’s weird not to give

  • Rodrigo, you are assigning the keypressed listerner to jbutton, you have to assign it to jtextfield, otherwise it really won’t work.

  • 1

    Got it! Thanks @Math

Show 5 more comments

1 answer

5


You can add the System directly to Jtextfield at the time it is created.

Below that 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 system to the writingTextField, and when a key is pressed it will enter the method in question. In the above example it only checks if it is a ENTER and prints an informative message.

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

  • Correct answer!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.