设置键盘监听
//需要点击一下按钮后,按钮获得焦点,才会触发以下方法
btn.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
switch (event.getCode()){
case A:
System.out.println("A");
break;
case B:
break;
case F10:
break;
default:
//其他键盘
break;
}
}
});
//松开键盘监听
btn.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
}
});
设置键盘快捷键
Button b2 = new Button("Hello")
// 第一种
KeyCombination kc1 = new KeyCodeCombination(KeyCode.C, KeyCombination.ALT_DOWN, KeyCombination.CONTROL_DOWN);
Mnemonic mnemonic1 = new Mnemonic(b2, kc1);
scene.addMnemonic(mnemonic1);
// 第二种
KeyCombination kc2 = new KeyCharacterCombination("O", KeyCombination.ALT_DOWN);
Mnemonic mnemonic2 = new Mnemonic(b2, kc2);
scene.addMnemonic(mnemonic2);
//一般建议用这种,前几种在兼容上似乎或多或少有些问题
KeyCombination kccb = new KeyCodeCombination(KeyCode.K,
KeyCombination.SHIFT_DOWN);
scene.getAccelerators().put(kccb, new Runnable() {
@Override
public void run() {
System.out.println("run");
}
});