在java swing中将焦点转移到JTextFields中

时间:2011-12-21 06:44:27

标签: java swing

  

可能重复:
  ENTER key using in JTextField java

我的摇摆表格中有4个JTextFields。在JTextField1中输入某些值后,我现在点击键盘上的Enter键,焦点需要在JTextField2中输入一定值后从JTextfield1转移到JTextField2并点击输入焦点需要转移到JTextField3这样我不知道如何这样做我使用的代码是

package focus;
import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

public class Main{

  public static void main(String[] argv) throws Exception {

    JTextField component = new JTextField(20);
    JTextField component1 = new JTextField(20);
    JTextField component2 = new JTextField(20);
    JTextField component3 = new JTextField(20);
    KeyListener kl=new KeyListener() {

            public void keyTyped(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            public void keyPressed(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
                int key = e.getKeyCode();
            if (key == KeyEvent.VK_ENTER)
              component.transferFocus();
            }

            public void keyReleased(KeyEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        };
    component.addFocusListener(new MyFocusListener<JTextField>());
    component1.addFocusListener(new MyFocusListener<JTextField>());
    component2.addFocusListener(new MyFocusListener<JTextField>());
    component3.addFocusListener(new MyFocusListener<JTextField>());
        JFrame f = new JFrame();
    f.setLayout(new FlowLayout());
    f.add(component1);
    f.add(component);
     f.add(component2);
      f.add(component3);
    f.pack();
    f.setVisible(true);

  }
}
class MyFocusListener <C extends JTextField> extends  FocusAdapter {
  //boolean showingDialog = false;
  public void focusGained(FocusEvent evt) {
    final JTextComponent c = (JTextComponent) evt.getSource();
    String s = c.getText();
    c.requestFocus();
    c.selectAll();
    for (int i = 0; i < s.length(); i++) {
   if (!Character.isDigit(s.charAt(i))) {
    c.setSelectionStart(i);
        c.setSelectionEnd(i);
        break;
    }
    }
  }

  public void focusLost(FocusEvent evt) {
    final JTextComponent c = (JTextComponent) evt.getSource();
    String s = c.getText();
   if (evt.isTemporary()) {
     return;
    }
    for (int i = 0; i < s.length(); i++) {
     if (!Character.isDigit(s.charAt(i))) {
        //System.out.println("must only contain digits");
        c.requestFocus();
        c.selectAll();
        break;
      }
    }

}
}

1 个答案:

答案 0 :(得分:0)

只需将ActionListeners添加到文本字段,然后从ActionEvent中添加对象。 然后使用transferFocus()方法将焦点转移到其他文本字段。