KisnardOnline KisnardOnline - 4 months ago 27
Java Question

KeyEvent getActionCommand for f9 key?

My code for handling some keypresses was working fine when the keyboard keys were all normal (a-z), but now I want to make the default screenshot key be F9.

if (e.getActionCommand().toUpperCase().equals(configFile.getProperty("TOGGLE_ATTACK_KEY"))){
inAttackMode = !inAttackMode;
} else if (e.getActionCommand().toUpperCase().equals(configFile.getProperty("SCREENSHOT_KEY"))){

e.getActionCommand() is returning null when I press the F9 key. The code to register this key is here:

theDesktop.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released " + configFile.getProperty("SCREENSHOT_KEY")), "f9ButtonRelease");
theDesktop.getActionMap().put("f9ButtonRelease", ClassKeyReleaseHandler);

Thanks for any help on this... I tried to search Google and SO but did not see anything specific. Also tried using VK_F9 to register, but it only fires with F9(either way it returns null when I press F9). Thanks for any help.


One of the reasons for using Key Bindings is to avoid the use of nested if/else statements. Instead you create a unique Action for the key binding, then the action command is irrelevant.

//theDesktop.getActionMap().put("f9ButtonRelease", ClassKeyReleaseHandler);
theDesktop.getActionMap().put("f9ButtonRelease", ScreenShotReleaseHandler);

This is the way all the default Actions are created in Swing.