• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3560
  • Last Modified:

To Capture 'Enter Key' on a JTextField

I want my program to perform a piece of code if I type something in a JTextfield and hit enter. How do I do it.

Examples would be appreciated.

Thanx In Advance

Bijoy
0
bijoyn
Asked:
bijoyn
  • 3
  • 2
1 Solution
 
giamtrotCommented:
I think this should work:


import java.awt.event.*;
import javax.swing.*;

public class enter
{
    public static void main(String args[])
    {
        JFrame frm = new JFrame();
        frm.getContentPane().setLayout(null);
        frm.addWindowListener(
            new WindowAdapter()
            {
                public void windowClosing( WindowEvent e )
                {
                    ((JFrame)e.getSource()).dispose();
                    System.exit(0);
                }
            }
        );
       
        JTextField jtf = new JTextField();
        jtf.setBounds(10, 10, 200, 30);
        jtf.setVisible(true);
       
        jtf.addKeyListener( new ifEnterKeyPressed() );
       
        frm.getContentPane().add(jtf);
        frm.setBounds(100, 100, 400, 400);
       
        frm.show();
    }
}

class ifEnterKeyPressed implements KeyListener
{
    public void keyPressed(KeyEvent e)
    {
        if ( e.getKeyCode() == KeyEvent.VK_ENTER )
            System.out.println("It works.");
    }
   
    public void keyReleased(KeyEvent e) {}
   
   
    public void keyTyped(KeyEvent e) {}
}

0
 
bijoynAuthor Commented:
I guess I was doing the same thing. Can u please tell me how to assign the value of the JTextField to a variable. I would then go ahead and accept your answer.

Thanks a million

Bijoy
0
 
objectsCommented:
You don't need a key listener.
An action event is fired when the <Enter> key is pressed.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
objectsCommented:
tf.addActionListener(new ActionListener()
   { public void actionPerformed(ActionEvent e) { enter(e); }});

..

private void enter(ActionEvent e)
{
   JTextField tf = (JTextField) e.getSource();
   System.out.println("Entered text: "+tf.getText());
}
0
 
giamtrotCommented:
The comment from objects shows out to get the text from the object:

you can take a reference to the object calling out of the event ( e.getSource() ) and then cast the generic object you get to a JTextField.
Now you have a full reference to the JTextField

0
 
objectsCommented:
It also shows that you don't need a key listener to know when the <Enter> is pressed :)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now