给你弄好了,见代码
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
public class mKeyListener implements KeyListener {
public void keyPressed(KeyEvent e) {
String name = ((JTextField) e.getSource()).getName();
if (name.equals("textField")) {
switch(e.getKeyCode()){
case 39:
textField_1.grabFocus();
break;
case 40:
textField_2.grabFocus();
break;
}
}else if(name.equals("textField_1")){
switch(e.getKeyCode()){
case 37:
textField.grabFocus();
break;
case 40:
textField_3.grabFocus();
break;
}
}else if(name.equals("textField_2")){
switch(e.getKeyCode()){
case 39:
textField_3.grabFocus();
break;
case 38:
textField.grabFocus();
break;
}
}else if(name.equals("textField_3")){
switch(e.getKeyCode()){
case 37:
textField_2.grabFocus();
break;
case 38:
textField_1.grabFocus();
break;
}
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
mKeyListener m1 = new mKeyListener();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setName("textField");
textField.setBounds(10, 10, 96, 32);
textField.requestFocus();
textField.addKeyListener(m1);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setName("textField_1");
textField_1.setBounds(152, 10, 114, 44);
textField_1.addKeyListener(m1);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setName("textField_2");
textField_2.setBounds(10, 75, 96, 49);
textField_2.addKeyListener(m1);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setName("textField_3");
textField_3.setBounds(162, 64, 104, 44);
textField_3.addKeyListener(m1);
contentPane.add(textField_3);
textField_3.setColumns(10);
}
}