[java] Detect enter press in JTextField

Is it possible to detect when someone presses Enter while typing in a JTextField in java? Without having to create a button and set it as the default.

This question is related to java swing jtextfield

The answer is


Add an event for KeyPressed.

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
  if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
      // Enter was pressed. Your code goes here.
   }
} 

If you want to set a default button action in a JTextField enter, you have to do this:

//put this after initComponents();

textField.addActionListener(button.getActionListeners()[0]);

It is [0] because a button can has a lot of actions, but normally just has one (ActionPerformed).


The other answers (including the accepted ones) are good, but if you already use Java8, you can do the following (in a shorter, newer way):

textField.addActionListener(
    ae -> {
        //dostuff
    }
);

As the accepted answer told, you can simply react with an ActionListener, which catches the Enter-Key.

However, my approach takes benefit of the functional concepts which was introduced in Java 8.

If you want to use the same action for example for a button and the JTextField, you can do the following:

ActionListener l = ae -> {
    //do stuff
}

button.addActionListener(l);
textField.addActionListener(l);

If further explaination is needed, please let me know!


public void keyReleased(KeyEvent e)
{
    int key=e.getKeyCode();
    if(e.getSource()==textField)
    {
        if(key==KeyEvent.VK_ENTER)
        { 
            Toolkit.getDefaultToolkit().beep();
            textField_1.requestFocusInWindow();                     
        }
    }

To write logic for 'Enter press' in JTextField, it is better to keep logic inside the keyReleased() block instead of keyTyped() & keyPressed().


Do you want to do something like this ?

JTextField mTextField = new JTextField();
    mTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                // something like...
               //mTextField.getText();
               // or...
               //mButton.doClick();
            }
        }

    });

First add action command on JButton or JTextField by:

JButton.setActionCommand("name of command");
JTextField.setActionCommand("name of command");

Then add ActionListener to both JTextField and JButton.

JButton.addActionListener(listener);
JTextField.addActionListener(listener);

After that, On you ActionListener implementation write

@Override
public void actionPerformed(ActionEvent e)
{
    String actionCommand = e.getActionCommand();

    if(actionCommand.equals("Your actionCommand for JButton") || actionCommand.equals("Your   actionCommand for press Enter"))
    {
        //Do something
    }
}

For each text field in your frame, invoke the addKeyListener method. Then implement and override the keyPressed method, as others have indicated. Now you can press enter from any field in your frame to activate your action.

@Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                //perform action
            }
        }

Just use this code:

SwingUtilities.getRootPane(myButton).setDefaultButton(myButton);

JTextField function=new JTextField(8);   
function.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent e){

                        //statements!!!

                }});

all you need to do is addActionListener to the JTextField like above! After you press Enter the action will performed what you want at the statement!


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to swing

Calling another method java GUI Read input from a JOptionPane.showInputDialog box Call japplet from jframe Java JTable getting the data of the selected row What does .pack() do? How to add row of data to Jtable from values received from jtextfield and comboboxes How can I check that JButton is pressed? If the isEnable() is not work? Load arrayList data into JTable How to draw a circle with given X and Y coordinates as the middle spot of the circle? Simplest way to set image as JPanel background

Examples related to jtextfield

Java - Check if JTextField is empty or not How to set the height and the width of a textfield in Java? getting integer values from textfield Restricting JTextField input to Integers Limiting the number of characters in a JTextField JTable - Selected Row click event How to Set Focus on JTextField? How to convert JTextField to String and String to JTextField? How to clear the JTextField by clicking JButton Detect enter press in JTextField