I have a JDialog that contains many rows of textfields and a submit button. I would like to know if it's possible to add an eventListener to the container to trigger the submit button.
            Asked
            
        
        
            Active
            
        
            Viewed 1,192 times
        
    2
            
            
        - 
                    1Looks like a palce for KeyBinding's usage – StanislavL Apr 29 '15 at 09:42
 - 
                    can you explain your question in more detail so that I can understand better what you actually want to do – Luffy Apr 29 '15 at 09:55
 - 
                    For better help sooner, please add a [mcve](http://stackoverflow.com/help/mcve) that illustrates the issue you have. Furthermore, it is difficult to tell what exactly you want to do; it may even be that listening to key presses might not be the right approach. – kiheru Apr 29 '15 at 09:56
 
2 Answers
2
            One convenient way to bind Enter to an Action is via the root pane's setDefaultButton() method. You can also use the Action in a key binding, as shown here.
JDialog d = new JDialog(…);
Action submit = new AbstractAction("Submit") {
    @Override
    public void actionPerformed(ActionEvent e) {
        // handle submit
    }
};
private JButton b = new JButton(submit);
…
d.getRootPane().setDefaultButton(b);
1
            
            
        Try adding
frame.getRootPane().setDefaultButton(button);
    // removing the binding for pressed
    frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(KeyStroke.getKeyStroke("ENTER"), "none");
    // retarget the binding for released
    frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(KeyStroke.getKeyStroke("released ENTER"), "press");
Or else do something like the following
 addKeyListener(new KeyListener(){  
       @Override
       public void keyPressed(KeyEvent ke)
       {
       if (e.getKeyCode().equals(KeyEvent.VK_ENTER))
         { 
      //copy paste the logic you wrote inside the ActionPerformed method
         }
      }});
      setFocusable(true);//Setting Focus true for ur container
      requestFocusInWindow();//Requesting the focus. Without this, KeyEvent will not trigger on your container
        Lalit Rao
        
- 551
 - 5
 - 22
 
- 
                    Object as JFrame is by default doesn't react to KeyEvents from KeyListener – mKorbel Apr 29 '15 at 13:48
 -