0

I have JDialog that contains many JTextFields and JLabels and jbutton. When any of these components(textfields or buttons) are focused and ESCAPE is typed I want to capture generated keyEvent in parent JDialog.

I know there is clear solution for this. I cannot find it on the net.

Thank you!

Volodymyr Levytskyi
  • 3,364
  • 9
  • 46
  • 83

1 Answers1

2

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)

alex2410
  • 10,904
  • 3
  • 25
  • 41