0

I've read several topics showing how to create a KeyBinding, however, none of them fully worked for me. My JFrame has a JMenuBar and for the items of the menu NetBeans is correctly generating code such as:

mniExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
    mniExit.setText(bundle.getString("Menu.File.Exit")); // NOI18N
    mniExit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            mniExitActionPerformed(evt);
        }
    });
mnuFile.add(mniExit);

However, only this binding is not visible when the menu is hidden. I've tried something like:

getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(mniExit.getAccelerator(), "exit");
getRootPane().getActionMap().put("exit", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            mniExit.doClick();
        }
    });

But it simply does not work. What am I doing wrong?

Thanks in advance!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 1
    If you don't get help soon, consider creating and posting a [minimal example program](http://sscce.org) where you create the smallest program that runs, compiles, requires no outside dependencies (images, database) and that demonstrates your problem for us. – Hovercraft Full Of Eels Jul 06 '15 at 15:25

1 Answers1

1

You state that

However, only this binding is not visible when the menu is hidden. I've tried something like:

I'm guessing here, but I'm not sure that a button or menu can be clicked if its not visible. To simplify, I would create an ExitAction class, a class that extends from AbstractAction, that is assigned as an Action to any JMenuItems, JButtons, or Key Bindings that need it. If they all share the same ExitAction object, then the Action (and the corresponding menu items and buttons) can be disabled all at once if need be.

If this does not help, again create and post a minimal example program where you create the smallest program that runs, compiles, requires no outside dependencies (images, database) and that demonstrates your problem for us.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks for the answer! The problem is not the call to doClick(), actually, I just found out this problem happens exclusively with the CTRL+X key stroke. All the other bindings (CTRL+O, CTRL+N, CTRL+S, CTRL+SHIFT+S) work, even when the items are hidden, however, CTRL+X does not. Is there any possibility this specific combination is being captured somewhere else? – Luciano Santos Jul 06 '15 at 15:54
  • You probably should not use Ctrl+X, Ctrl+C, or Ctrl+V for menu accelerators, since they will conflict with cut/copy/paste behavior of any text fields in your app. – FredK Jul 06 '15 at 17:23