让用户定义键盘快捷键

Let user define keyboard shortcut

为了简化我的 JavaFx 应用程序的使用,我希望允许用户定义键盘组合/快捷方式来触发应用程序最重要的操作。

我知道如何在代码中定义 KeyCodeCombination 并将其设置为 Accelerator 或在 KeyEvent 侦听器中使用它,但我不想对其进行硬编码,而是希望允许用户只需在某个设置对话框中按键盘上的键即可定义自己的 KeyCodeCombination。

基本上是这个伪代码:

// how would I implement the next two lines
Dialog dialog = new KeyboardShortcutDefinitionDialog();
KeyCombination shortcut = dialog.recordKeyboardShortcut();

// I know how to do the rest from here
shortcutLabel.setText(shortcut.toString());
SettingsManager.storeShortcut(shortcut);
Application.setupShortcut(shortcut);

这是一个监听 KEY_PRESSED 事件并从中构建 KeyCombination 的小示例。

import java.util.ArrayList;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyCombination.Modifier;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        var label = new Label();
        label.setFont(Font.font("Segoe UI", 15));
        primaryStage.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
            if (!event.getCode().isModifierKey()) {
                label.setText(createCombo(event).getDisplayText());
            }
        });

        primaryStage.setScene(new Scene(new StackPane(label), 500, 300));
        primaryStage.setResizable(false);
        primaryStage.show();
    }

    private KeyCombination createCombo(KeyEvent event) {
        var modifiers = new ArrayList<Modifier>();
        if (event.isControlDown()) {
            modifiers.add(KeyCombination.CONTROL_DOWN);
        }
        if (event.isMetaDown()) {
            modifiers.add(KeyCombination.META_DOWN);
        }
        if (event.isAltDown()) {
            modifiers.add(KeyCombination.ALT_DOWN);
        }
        if (event.isShiftDown()) {
            modifiers.add(KeyCombination.SHIFT_DOWN);
        }
        return new KeyCodeCombination(event.getCode(), modifiers.toArray(Modifier[]::new));
    }

}