Can't remap Swing key binding for "enter"
I'm using swing key-bindings in a scala program. I'm trying to capture key-input in a JPanel. For some reason I can't remap the enter-key. shift-enter works and other keys work as well. What is special about enter? Below is a code snippet from my JPanel:
val ADD_SIBLING_TO_SELECTED = "add-sibling-to-selected"
val enter = KeyStroke.getKeyStroke("shift ENTER")//todo: figu开发者_高级运维re out why plain enter does not work
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(enter)
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(enter, ADD_SIBLING_TO_SELECTED)
import java.awt.event.ActionEvent
getActionMap().put(ADD_SIBLING_TO_SELECTED, new AbstractAction {
override def actionPerformed(e: ActionEvent){
println(ADD_SIBLING_TO_SELECTED)
}
})
Nothing special to the ENTER as such, only happens to be the most used gesture for indicating "ready" :-) So there's a non-zero probability that the ENTER might be already bound somewhere else. One candidate could be a default button registered in the frame's rootpane. Also note that the WHEN_IN_FOCUSED_WINDOW type binding is the very last to be queried.
CU Jeanette
Strange; that works on my machine. Tried it with this complete code on scala 2.8.1 on mac os x 10.6.7 with jdk 1.6.0_24:
object ShowKeyPress {
def main(args: Array[String]) {
import javax.swing._
val frame = new JFrame
frame.setVisible(true)
frame.add(new JPanel {
val ADD_SIBLING_TO_SELECTED = "add-sibling-to-selected"
val enter = KeyStroke.getKeyStroke("ENTER")
//todo: figure out why plain enter does not work
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(enter)
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(enter, ADD_SIBLING_TO_SELECTED)
import java.awt.event.ActionEvent
getActionMap().put(ADD_SIBLING_TO_SELECTED, new AbstractAction {
override def actionPerformed(e: ActionEvent) {
println(ADD_SIBLING_TO_SELECTED)
}
})
})
}
}
It turns out that I needed to call requestFocusInWindow()
and use WHEN_FOCUSED
and everything worked. I'm still not sure why shift-enter worked but enter did not. Thanks for the feedback!
精彩评论