Read more about key bindings.
Try next code it can help you:
public static void main(String[] args) {
JFrame f = new JFrame();
JTextField field =new JTextField();
f.getContentPane().add(field,BorderLayout.SOUTH);
((JPanel)f.getContentPane()).getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("F2"), "doSomething");
((JPanel)f.getContentPane()).getActionMap ().put("doSomething", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("test");
}
});
f.getContentPane().add(new JLabel("1"),BorderLayout.NORTH);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
Use next construction getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
because of: The component contains (or is) the component that has the focus. This input map is commonly used for a composite component — a component whose implementation depends on child components.(according to docs)