javaswingkey-bindingsfocusmanager

Focus navigation in keyBinding


In my form, when i press ENTER button in my keyboard, the okAction() method should be invoke (and invoke perfectly).

My problem is in focus state, When i fill the text fields and then press the ENTER button, the okAction() didn't invoked, because the focus is on the second text field (not on the panel).

How fix this problem?

public class T3 extends JFrame implements ActionListener {

JButton cancelBtn, okBtn;
JLabel fNameLbl, lNameLbl, tempBtn;
JTextField fNameTf, lNameTf;

public T3() {
    add(createForm(), BorderLayout.NORTH);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 500);
    setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new T3();
        }
    });
}

public JPanel createForm() {
    JPanel panel = new JPanel();
    panel.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "Button");
    panel.getActionMap().put("Button", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            okAction();
        }
    });

    okBtn = new JButton("Ok");
    okBtn.addActionListener(this);
    cancelBtn = new JButton("Cancel");
    tempBtn = new JLabel();
    fNameLbl = new JLabel("First Name");
    lNameLbl = new JLabel("Last Name");
    fNameTf = new JTextField(10);
    fNameTf.setName("FnTF");
    lNameTf = new JTextField(10);
    lNameTf.setName("LnTF");

    panel.add(fNameLbl);
    panel.add(fNameTf);
    panel.add(lNameLbl);
    panel.add(lNameTf);
    panel.add(okBtn);
    panel.add(cancelBtn);
    panel.add(tempBtn);

    panel.setLayout(new SpringLayout());
    SpringUtilities.makeCompactGrid(panel, 3, 2, 50, 10, 80, 60);
    return panel;
}

private void okAction() {
    if (fNameTf.getText().trim().length() != 0 && lNameTf.getText().trim().length() != 0) {
        System.out.println("Data saved");
    } else System.out.println("invalid data");
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == okBtn) {
        okAction();
    }
}
}

Solution

  • Declare a default button for your GUI's JRootPane:

    public T3() {
    
      //!! ..... etc...
    
      setVisible(true);
      getRootPane().setDefaultButton(okBtn);
    }
    

    In fact with a default button set, I don't see that you need to use key bindings.