For your use case, I think you really want to use the accelerator, not the mnemonics.
button.getScene().getAccelerators().put( new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN), new Runnable() { @Override public void run() { button.fire(); } } );
In most cases, it is recommended to use KeyCombination.SHORTCUT_DOWN as a modifier specifier, as in the code above. A good explanation of this in the KeyCombination documentation:
The shortcut modifier is used to represent the modifier key, which is commonly used in keyboard shortcuts on the host platform. This is for example management on Windows and meta (command key) on Mac. Using developers, shortcut keys can create platform-independent shortcuts. Thus, the keyboard shortcut βShortcut + Cβ is processed internally as βCtrl + Cβ on Windows and βMeta + Cβ on Mac.
If you want to specifically encode only the keyboard shortcut Ctrl + S, you can use:
new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN)
Here is an example:
import javafx.animation.*; import javafx.application.Application; import javafx.event.*; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.input.*; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.util.Duration; public class SaveMe extends Application { @Override public void start(final Stage stage) throws Exception { final Label response = new Label(); final ImageView imageView = new ImageView( new Image("http://icons.iconarchive.com/icons/gianni-polito/colobrush/128/software-emule-icon.png") ); final Button button = new Button("Save Me", imageView); button.setStyle("-fx-base: burlywood;"); button.setContentDisplay(ContentDisplay.TOP); displayFlashMessageOnAction(button, response, "You have been saved!"); layoutScene(button, response, stage); stage.show(); setSaveAccelerator(button); }
Output Example:

jewelsea
source share