如何使用getKeyStroke(String s)方法?

时间:2018-04-28 02:20:08

标签: java key-bindings keystroke

Link to the JavaDoc

我正在尝试在发布密钥时获取事件。我已经尝试格式化字符串,就像在文档中说的那样,但它只是使该键无响应。这是代码的工作线:

getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN"), MOVE_DOWN);

现在我想在发布密钥时让它做一些事情,所以尝试按照文档中的格式,我已经单独尝试了以下几行,但它们都使密钥无响应:

1. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN | pressed"), MOVE_DOWN);
2. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN | released"), MOVE_DOWN);
3. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN | true"), MOVE_DOWN);
4. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN | false"), MOVE_DOWN);
5. getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN, true"), MOVE_DOWN);
6. getInputMap(IFW).put(KeyStroke.getKeyStroke("VK_DOWN, false"), MOVE_DOWN);
7. getInputMap(IFW).put(KeyStroke.getKeyStroke("KeyEvent.VK_DOWN, false"), MOVE_DOWN);

你可能明白了......我不知道如何为此格式化字符串并且碰到了砖墙。

  1. 我应该如何为此格式化字符串?
  2. 我看到还有其他方法,我会更好地使用其中一种,以及如何使用?
  3. 我觉得getKeyStroke(char keyChar,boolean onKeyRelease)是我最好的选择,但它说它已被弃用了所以我应该完全避免使用那个吗?

1 个答案:

答案 0 :(得分:0)

Its documentation似乎很清楚。我们可以使用以下内容更正您的示例:

getInputMap(IFW).put(KeyStroke.getKeyStroke("pressed DOWN"), MOVE_DOWN);
getInputMap(IFW).put(KeyStroke.getKeyStroke("released DOWN"), MOVE_DOWN);

请注意,以下内容相当于"pressed DOWN"

getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN"), MOVE_DOWN);