设置键盘监听

  1. //需要点击一下按钮后,按钮获得焦点,才会触发以下方法
  2. btn.setOnKeyPressed(new EventHandler<KeyEvent>() {
  3. @Override
  4. public void handle(KeyEvent event) {
  5. switch (event.getCode()){
  6. case A:
  7. System.out.println("A");
  8. break;
  9. case B:
  10. break;
  11. case F10:
  12. break;
  13. default:
  14. //其他键盘
  15. break;
  16. }
  17. }
  18. });
  19. //松开键盘监听
  20. btn.setOnKeyReleased(new EventHandler<KeyEvent>() {
  21. @Override
  22. public void handle(KeyEvent event) {
  23. }
  24. });

设置键盘快捷键

  1. Button b2 = new Button("Hello")
  2. // 第一种
  3. KeyCombination kc1 = new KeyCodeCombination(KeyCode.C, KeyCombination.ALT_DOWN, KeyCombination.CONTROL_DOWN);
  4. Mnemonic mnemonic1 = new Mnemonic(b2, kc1);
  5. scene.addMnemonic(mnemonic1);
  6. // 第二种
  7. KeyCombination kc2 = new KeyCharacterCombination("O", KeyCombination.ALT_DOWN);
  8. Mnemonic mnemonic2 = new Mnemonic(b2, kc2);
  9. scene.addMnemonic(mnemonic2);
  10. //一般建议用这种,前几种在兼容上似乎或多或少有些问题
  11. KeyCombination kccb = new KeyCodeCombination(KeyCode.K,
  12. KeyCombination.SHIFT_DOWN);
  13. scene.getAccelerators().put(kccb, new Runnable() {
  14. @Override
  15. public void run() {
  16. System.out.println("run");
  17. }
  18. });