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 C ompose 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.
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.