如何在 javafx 中为 Button 设置加速器(键盘快捷键)

How to set Accelerator (keyboard shortcut) for Button in javafx

如何在相同的letter.In中设置助记符解析我的项目在按钮中设置了助记符,但是按钮setText在每个事件动作中都发生了变化,但是助记符在_o中是相同的但是很短只能使用一个键 event.How 来解决这个问题

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @author user
 */
public class JavaFXApplication4 extends Application {
    boolean b = false;
    @Override
    public void start(Stage primaryStage) {

    Button btn = new Button();
    btn.setText("Hell_o");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
           b = !b;
           if(!b){
              btn.setText("Hell_o");
               System.out.println("Hello");
           } else {
               btn.setText("w_orld");
               System.out.println("world");
           }
        }
    });

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    launch(args);
    }

}

对不起我的English

您需要在文本更改前关闭助记符解析,更改后重新开启助记符解析。 setText()方法没有实现任何助记符的刷新,所以看起来一切都在场景中完成。

public class JavaFXApplication4 extends Application {

  boolean b = false;

  @Override
  public void start(Stage primaryStage) {

    Button btn = new Button();
    btn.setMnemonicParsing(true);
    btn.setText("Hell_o");
    btn.setOnAction(new EventHandler<ActionEvent>() {

      @Override
      public void handle(ActionEvent event) {
        b = !b;
        btn.setMnemonicParsing(false);
        if (!b) {
          btn.setText("Hell_o");
          System.out.println("Hello");
        } else {
          btn.setText("W_orld");
          System.out.println("World");
        }
        btn.setMnemonicParsing(true);
      }
    });

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    launch(args);
  }
}