Q:

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

How to set on Mnemonic Parsing in same letter.In my project set Mnemonic in button, but button setText Change in every Event action,but Mnemonic is same in _o but short keys working only one event.How to solve this problem
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);
    }

}

sorry for my English

A:

You need to switch off mnemonic parsing before the text change, and after the change switch it on again. The method setText() does not implement any refreshing for mnemonic so it seems that all is done in the Scene.
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);
  }
}

