Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

UPDATE: not relevant for OP's question.

If you want to use the constant KeyEvent.VK_F9. You should not be using e.getActionCommand, but e.getKeyCode.

for example:

    public class TestListener implements KeyListener{
    public void keyPressed(KeyEvent e){
        if(e.getKeyCode() == KeyEvent.VK_F9)
            System.out.println("F9 is pressed");

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top