0

I am using following code to set shortcut keys for my JFrame.

KeyboardFocusManager keyManager;
keyManager=KeyboardFocusManager.getCurrentKeyboardFocusManager();
keyManager.addKeyEventDispatcher(new KeyEventDispatcher() {
     @Override
     public boolean dispatchKeyEvent(KeyEvent e){
          if(e.getID()==KeyEvent.KEY_PRESSED && e.getKeyCode()==KeyEvent.VK_C && e.isShiftDown()){
               //shift+c
               openCalculator();
          }
     return false;
}});

And it works fine! but the problem is that when user is writing something in some textfield or table cells etc. and wants to write any capital letter let's say Compose and presses Shift+C to capitalise then my code accepts this as a shortcut key and instead of writing the capital letter that event is fired.

What I want to do is disable this event for all editable cells, fields etc through out the program And enable it back again when the editable component loses focus. I want my shortcut keys to only work when user is not editing any field or writing something in the program.

  • Create a list of editable fields, and use an if statement to cycle through all editable fields and do nothing with your shortkeys if one of them has focus, or, make sure every editable field has a focus/unfocus event that sets a boolean value for your shortkeys to check if they should trigger or not? – sorifiend Oct 28 '20 at 05:16
  • thank you for the comment! I thought of this too but I was hoping for a way around that because I have too many fields and even have some editable tables in my project too. maybe something like UIManger.put("JTEXTFIELD.IsFocued","disable shortkeys"); type code for all editable fields. BTW I used UIManager to set disabled text color for all JLabels that's why I am referring to this here. –  Oct 28 '20 at 05:34
  • You can do exactly that, just make a wrapper around a list that keeps a reference to the editable objects. Or, just add a check to each shortkeys `if(yourJFrame.getFocusOwner().isEditable == false){do short keys here}`, but that may misfire for some things. – sorifiend Oct 28 '20 at 06:08

1 Answers1

1

I resolved this with a check on KeyDispatchEvent by identifying specific instances of the components on which I don't want my event to work when focused.

boolean check = true;
try 
{
    Component comp = FocusManager.getCurrentManager().getFocusOwner();
    if(comp instanceof JTextField || comp instanceof JTextArea || comp instanceof JComboBox || comp instanceof JTable){
         check = false;
     } 
     } catch (Exception ee) { ee.printStackTrace();
        check = true;
      }
}
if (check)
{
      //do something
}