Solved

KeyListener

Posted on 1998-08-13
6
374 Views
Last Modified: 2010-08-05
I know TextFields can travel by "Tab".  How can we make all TextFields traversable by pressing "Enter"?
Could you please give me an example code?
0
Comment
Question by:AmyS
  • 3
  • 2
6 Comments
 

Expert Comment

by:tarlton
ID: 1232711
You need to add a keyListener to your text fields.  Here is an example:

JTextField m_textField;
JTextField m_secondTextField;
JTextField m_thirdTextField;
m_textField.addKeyListner(new HandleEnterPress());
m_secondTextField.addKeyListner(new HandleEnterPress());
m_thirdTextField.addKeyListner(new HandleEnterPress());

    /**
     * The CHandleEnterPress class controls the focus when the Enter key is
     * pressed.
     **/
      class CHandleEnterPress extends KeyAdapter
      {
          /**
           * called when any key is pressed
           **/
        public void keyPressed(KeyEvent e)
        {
            if (e.getKeyCode() == KeyEvent.VK_ENTER)
            {
                if (e.getSource() == m_textField)
                {
                    m_secondTextField.requestFocus();
                }
                else if (e.getSource() == m_secondTextField)
                {
                    m_thirdTextField.requestFocus();
                }
            }
        }
    }

0
 

Author Comment

by:AmyS
ID: 1232712
tarlton,
Your code is good for a couple of TextFields. But I want to search for a better way which
can easily handle more than 20 TextFields traversable by pressing "Enter".
0
 
LVL 4

Expert Comment

by:evijay
ID: 1232713
When enter key is pressed, the ActionEvent is generated. In the action listener's actionPerformed method, put a one liner. The code is below

public class TextAction implements ActionListener {
public void actionPerformed(ActionEvent e)
{
   e.getSource().transferFocus(); // moves to next field
}


in your code attach action listener as follows

TextAction ta = new TextAction();

for each text field tf add,

tf.addActionListener(ta);




Second method :

Extend TextField class

public class MyTextField extends TextField Implements ActionListener {
 public MyTextField (String text) {
  super(text);
  addActionListener(this);
 }
 public MyTextField () {
  super();
  addActionListener(this);
 }

public void actionPerformed(ActionEvent e)

{
   e.getSource().transferFocus(); // moves to next field
}




}
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:AmyS
ID: 1232714
Hi Evijay,
When I wrote a small code to test your answer, I got an error message:
Method transferFocus() not found in class java.lang.Object.
         e.getSource().transferFocus();
Here is the test code:


   import java.awt.*;
   import java.awt.event.*;

   public class Test1 extends Panel
   {
       myTextField first, last, company, address, home, work;
       
       public Test1()
       {
         
           setBackground(Color.lightGray);

           setLayout(new GridLayout(7,2,5,5));

           add(new Label("First Name"));
           first = new myTextField("first_name");
           add(first);        
                   
           add(new Label("Last Name"));
           last = new myTextField("last_name");
           add(last);

           add(new Label("Company Name"));
           company = new myTextField("company_name");
           add(company);

           add(new Label("Address"));
           address = new myTextField("726 Forest Dr.");
           add(address);

           add(new Label("Home Phone #"));
           home = new myTextField("home_phone");
           add(home);
           
           add(new Label("Work Phone #"));
           work = new myTextField("work_phone");
           add(work);

         
       }
       
     
       
       public Dimension getPreferredSize()
       {
           return new Dimension(300, 200);
       }

       public static void main(String s[])
       {
           Frame frame = new Frame("Focus Example");
           Test1 panel = new Test1();

           frame.add(panel,"Center");
           frame.setSize(panel.getPreferredSize());
           frame.setVisible(true);
       }
       
     
   public class myTextField extends TextField implements ActionListener {
    public myTextField (String text) {
     super(text);
     addActionListener(this);
    }
    public myTextField () {
     super();
     addActionListener(this);
    }

   public void actionPerformed(ActionEvent e)

   {
      e.getSource().transferFocus(); // moves to next field
   }
       
     
   }
}





0
 
LVL 4

Accepted Solution

by:
evijay earned 40 total points
ID: 1232715
I am very sorry. You need to cast the result of getSource. It should be like this

 ((Component) (e.getSource())).transferFocus();
0
 
LVL 4

Expert Comment

by:evijay
ID: 1232716
Here is working code :



                import java.awt.*;
                import java.awt.event.*;

                public class Test1 extends Panel
                {
                    myTextField first, last, company, address, home, work;
                     
                    public Test1()
                    {
                       
                        setBackground(Color.lightGray);

                        setLayout(new GridLayout(7,2,5,5));

                        add(new Label("First Name"));
                        first = new myTextField("first_name");
                        add(first);          
                                 
                        add(new Label("Last Name"));
                        last = new myTextField("last_name");
                        add(last);

                        add(new Label("Company Name"));
                        company = new myTextField("company_name");
                        add(company);

                        add(new Label("Address"));
                        address = new myTextField("726 Forest Dr.");
                        add(address);

                        add(new Label("Home Phone #"));
                        home = new myTextField("home_phone");
                        add(home);
                         
                        add(new Label("Work Phone #"));
                        work = new myTextField("work_phone");
                        add(work);

                       
                    }
                     
                   
                     
                    public Dimension getPreferredSize()
                    {
                        return new Dimension(300, 200);
                    }

                    public static void main(String s[])
                    {
                        Frame frame = new Frame("Focus Example");
                        Test1 panel = new Test1();

                        frame.add(panel,"Center");
                        frame.setSize(panel.getPreferredSize());
                        frame.setVisible(true);
                    }
                     
                   
                public class myTextField extends TextField implements ActionListener {
                 public myTextField (String text) {
                  super(text);
                  addActionListener(this);
                 }
                 public myTextField () {
                  super();
                  addActionListener(this);
                 }

                public void actionPerformed(ActionEvent e)

                {
                   ((Component)e.getSource()).transferFocus(); // moves to next field
                }
                     
                   
                }
             }

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
splitOdd10 challenge 5 74
Systems talking to each other 5 124
javap bin 2 26
difference of if loops 23 39
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now