Results 1 to 4 of 4
  1. #1
    userno69 is offline Member
    Join Date
    Nov 2011
    Posts
    2
    Rep Power
    0

    Default Press enter on JTextField to make focus on next JTextField?

    I am fairly new to Java and I have a simple question about JTextFields. I have a logon window with a JTextField and a JPasswordField, the text field is for the username and the password field is for the password. I want to set up the JTextField so when you press enter on it, it will automatically change the focus to the password field.

    I think this could be done by having it set up so a keypress of tab is registered when the user presses enter on the username. How would I go about doing this?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Press enter on JTextField to make focus on next JTextField?

    Pressing *Enter* in a JTextField will call any ActionListeners that have been added to that field, if any, and so you can add an ActionListener to your JTextField that requests focus on the JPasswordField.

  3. #3
    userno69 is offline Member
    Join Date
    Nov 2011
    Posts
    2
    Rep Power
    0

    Default Re: Press enter on JTextField to make focus on next JTextField?

    Thanks, I tried to do that but couldn't figure out how... I did get it to work using the Robots class to simulate a press of the tab button, but there are situations where that might not work and it is probably less efficient. Can you provide an example line of code that sets the focus to a specific JTextField/JPasswordField?

  4. #4
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: Press enter on JTextField to make focus on next JTextField?

    Get rid of the Robot. That is the wrong approach.

    In your ActionListener you can use:
    Java Code:
    JComponent component = event.getSource();
    component.transferFocus();

Similar Threads

  1. Give Focus to JTextField within JList
    By sycosquirl18 in forum AWT / Swing
    Replies: 2
    Last Post: 11-06-2011, 11:28 PM
  2. How to make JTextField Displayer?
    By winston in forum New To Java
    Replies: 4
    Last Post: 10-14-2011, 03:33 AM
  3. Replies: 9
    Last Post: 06-16-2010, 04:42 AM
  4. Replies: 1
    Last Post: 01-30-2009, 07:44 PM
  5. how to focus to another JTextfield?
    By birdofprey in forum AWT / Swing
    Replies: 2
    Last Post: 04-09-2008, 02:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •