javaswingkeyeventjmenubar

Need to disable F10 key's Frame Focus in swing applet


i am using F10 as shortcut for update data into database.whenever i press F10 Updates Works Fine but.my Focus Moved to Menu bar(the bar contains close,minimize,maximize) is there anyway to stop this?i know this is windows shortcut.is that possible to stop it?


Solution

  • You may try to remove the WHEN_IN_FOCUSED_WINDOW action from your JMenuBar. Just add this line into your code :

    menuBar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F10"), "none");
    

    Where the menuBar is the reference for your JMenuBar component.

    EDIT :

    Indeed, in case you're not using JMenuBar the above solution does not work. An alternative solution is to create an empty action and use it to bind the F10 key. (see [Key Bindings][1]).

    Here is an example :

     //create an empty action which do nothing
    Action emptyAction = new AbstractAction(){
         public void actionPerformed(ActionEvent e)
         {   //do nothing here   }};
    
    //bind F10 with the empty action
    KeyStroke f10 = KeyStroke.getKeyStroke( "F10");
    frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(f10, "F10");
    frame.getRootPane().getActionMap().put("F10", emptyAction);
    

    Where frame is your JFrame component. [1]: https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html