"Fereshteh Shojaei" <fe****************@comhem.se> wrote in message news:<SA********************@newsc.telia.net>...
Hi,
I wonder if somebody could help me. I would like to move the cursor from one
JTextField to another one when I press <CR>.
Regards,
Fereshteh
Hello Fereshteh,
One solution to your problem involves calling a component's
requestFocus() method from within another component's action listener.
To demonstrate, I've created a MoveCursor.java program. The source
code appears below:
// MoveCursor.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MoveCursor
{
static JTextField t1, t2;
public static void main (String [] args)
{
JFrame f = new JFrame ("Move Cursor");
f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel (new FlowLayout (FlowLayout.LEFT));
JLabel l = new JLabel ("Name:");
p.add (l);
t1 = new JTextField (20);
t1.addActionListener (new ActionListener ()
{
public void actionPerformed
(ActionEvent e)
{
t2.requestFocus ();
}
});
p.add (t1);
f.getContentPane ().add (p, BorderLayout.SOUTH);
p = new JPanel (new FlowLayout (FlowLayout.LEFT));
l = new JLabel ("Address:");
p.add (l);
t2 = new JTextField (20);
t2.addActionListener (new ActionListener ()
{
public void actionPerformed
(ActionEvent e)
{
t1.requestFocus ();
}
});
p.add (t2);
f.getContentPane ().add (p, BorderLayout.NORTH);
f.setSize (350, 100);
f.setResizable (false);
f.setVisible (true);
}
}
Although I haven't commented the code, note that the t1-referenced
JTextField invokes t2.requestFocus (); from within its action
listener. This causes focus to shift to the t2-referenced JTextField
when the <CR> key is pressed. The same idea holds with the other
JTextField.
I hope this answers your question. For more help with Java, please
visit my Web site at
http://www.javajeff.net
Have a good day.
Jeff