How does a swing component makes a look up in its ActionMap from it's inputMap using the intermediate Object reference
I've been reading about registering the "Action" objects with multiple components, and I came across the recipe of registering (binding) an Action object to a Keystroke object.
In the pursuit I came across this piece of code:
InputMap imap = panel.getInputMap(JComponent.WHEN_FOCUSED);
imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
ActionMap amap = panel.getActionMap();
amap.put("panel.yellow", yellowAction)
Now the way it works is that there is one level of indirection to registering your keystrokes with Action objects. Firstly you associate a keystroke to some arbitrary object in one of the Input maps (in our example it is map corresponding to WHEN_FOCUSED constant) of the Component and secondly you register the action with the same reference, in another map, ActionMap, maintained by the component.
Now my doubt is that, If I assume that semantics of mapping the keystroke to action objects, is done by using the similarity of intermediate object reference residing in these two maps, then where is the guarantee that this equality will always hold, unless the object reference I used has indeed define a valid notion of equality (or hashcode).
For instance, in my example, I'm attaching keystroke with an instance of String "panel.yellow" in one of the InputM开发者_运维知识库aps, then I'm trying to attach an action object with same String "panel.yellow" in ActionMap of Panel. Now, theoretically, JVM doesn't guarantee that both these String instances (which I've hardcoded) will be referring to same String object! And worse, if JVM doesn't supply a notion of content equality for Strings, then there is no way, my action object can be successfully mapped to my keystroke. This is just as true for any object which I may use to intermediately bind keystroke with action objects, and for which I have not defined any notion of equality (or hashcode) other than the reference equality that Object class defines.
Can anybody please clarify this.
AViD
You're right that both strings may not be the same object, but you can check for equality using the equals(...)
method, which is likely to be used to map your action to the key stroke.
Note that besides hashCode
every object also provides for an equals(...)
method, which might be the same as ==
for arbitrary objects, but String
overrides it for content equality checks (which you would also do, if you'd override that method for custom objects).
Strings are interned by default so they will be the same object. See the String.intern() method for more info.
But if you really are concerned about this then the simple solution is to use the same object reference in the InputMap and ActionMap.
Check out the example code from Key Bindings that shows how I do this.
精彩评论