Search code examples
javakeystroke

Get the parameters of a method in a anonymous class


I have a question concerning the key bindings. I have the following Java code:

private void registerPressedReleasedKey(String keyChar, boolean key, boolean pressedKey) {

    // 1. decide if the key is pressed or released
    // 2. save key and its action name
    // 3. decide, what to do, when the action name is being mentioned
    // 4. change the boolean value in actionPerformed(ActionEvent ae)

    String keyStatus;

    if(pressedKey == true)
        keyStatus = "pressed ";
    else
        keyStatus = "released ";
            getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(keyStatus + keyChar), keyStatus + keyChar);
    getActionMap().put(keyStatus + keyChar, new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            key = pressedKey;
        }
    });
}

Eclipse says to me that key = keyPressed; is wrong, because I only can use final variables. My question is if there is a possibility to access and change key inside the actionPerformed(ActionEvent ae) method.


Solution

  • Answering your question

    It is impossible to modify external variables in an anonymous class the way you are trying to since these must be final.

    If this was a field of your class, you could use access it directly (in Java > 7) or use an accessor (setter). Since it is not, the way to go would be to use a wrapper: final means you cannot assign a new value, but you can still call its methods and any accessor is basically a method.

    Warning notice

    I assume your code is incomplete, as in this example, you try to set the variable key, which is not used anywhere.

    However, assigning a new value to a parameter is generally a bad practice.

    Moreover, getActionMap() & AbstractAction suggest that a Swing component is being used, which means that actionPerformed() will get called by Swing thread, probably even after registerPressedReleaseKey() has finished. As a consequence, updating a parameter for this method makes no sense.