[Notes] javafx set shortcut keys _ five methods

The contents of several shortcut keys are in order:
ctrl+alt+C
alt+J The
third type has not tried
ctrl+Y
ctrl+alt+K and
then the relevant content is printed out.

//设置快捷键,使用按钮的快捷键相当于点击了按钮
/*
* 快捷键要添加到场景图中
* */
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class Main_快捷键 extends Application {
    
    
    public static void main(String[] args) {
    
    
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
    
    
        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color:#7AC5CD");

        Button bu1 = new Button("button1");
        an.getChildren().add(bu1);
        bu1.setOnAction(new EventHandler<ActionEvent>() {
    
    
            @Override
            public void handle(ActionEvent event) {
    
    
                System.out.println(bu1.getText());
            }
        });
        Scene scene = new Scene(an);

        //第一种 -用的比较多
        KeyCombination kc1 = new KeyCodeCombination(KeyCode.C, KeyCombination.ALT_DOWN, KeyCombination.CONTROL_DOWN);
        Mnemonic mnemonic1 = new Mnemonic(bu1,kc1);
        scene.addMnemonic(mnemonic1);

        //第二种 -几乎没用
        KeyCombination kc2 = new KeyCharacterCombination("J", KeyCombination.ALT_DOWN);
        Mnemonic mnemonic2 = new Mnemonic(bu1,kc2);
        scene.addMnemonic(mnemonic2);
        //第三种 -几乎没用过
        KeyCombination kc3 = new KeyCodeCombination(KeyCode.A, KeyCombination.SHIFT_DOWN, KeyCombination.CONTROL_DOWN,KeyCombination.ALT_DOWN, KeyCombination.META_DOWN,KeyCombination.SHORTCUT_DOWN);
        Mnemonic mnemonic3 = new Mnemonic(bu1,kc3);
        scene.addMnemonic(mnemonic3);
        //第四种 -用的最多 在win和 mackintosh 都适用
        KeyCombination kccb = new KeyCodeCombination(KeyCode.Y, KeyCombination.SHORTCUT_DOWN);
        scene.getAccelerators().put(kccb, new Runnable() {
    
    //其实还是当前线程执行
            @Override
            public void run() {
    
    
                System.out.println("Run方法的执行者 = " + Thread.currentThread().getName());
            }
        });
        //第五种
        KeyCombination kc5 = KeyCombination.valueOf("ctrl+alt+k");
        Mnemonic mnemonic5 = new Mnemonic(bu1, kc5);
        scene.addMnemonic(mnemonic5);

        primaryStage.setScene(scene);
        primaryStage.setTitle("JavaFX");
        primaryStage.setWidth(800);
        primaryStage.setHeight(800);
        primaryStage.show();
    }
}

Reference:
https://www.bilibili.com/video/BV1JW41167iU
https://www.bilibili.com/video/BV1bW41117hW/?spm_id_from=333.788.videocard.0

Guess you like

Origin blog.csdn.net/qq_43750882/article/details/110143664