In my form, when I press the ENTER button on my keyboard, the okAction() method should be invoked (and invoked perfectly).
My problem is the focus state. When I fill in the text fields and then press the ENTER button, okAction() not called because the focus is in the second text field (and not on the panel).
How to 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(); } } }
Sajad source share