12

Take for example the menu items from the edit menu in JavaFX Scene Builder

See how they display the shortcuts on the right? Is there any easy way to achieve the same effect using JavaFX? Thanks.

Nicolas Martel
  • 1,641
  • 3
  • 19
  • 34

2 Answers2

18

You can add an accelerator key in scene builder or add it directly in the fxml file like so

<?import javafx.scene.input.*?>
...
<MenuItem mnemonicParsing="true" onAction="#mnuSaveAction" text="%menu.title.save" fx:id="mnuSave">
   <accelerator>
      <KeyCodeCombination alt="UP" code="S" control="DOWN" meta="UP" shift="UP" shortcut="UP" />
   </accelerator>
</MenuItem>

KeyCodeCombination has two constructors, second example:

<MenuItem text="Renommer..."      onAction="#rename" mnemonicParsing="true">
   <accelerator>
      <KeyCodeCombination code="F2"><modifiers></modifiers></KeyCodeCombination>
   </accelerator>
</MenuItem>

If by "in javafx" you mean without using fxml you can use mnuSave.setAccelerator(KeyCombination);

Aubin
  • 14,617
  • 9
  • 61
  • 84
brian
  • 10,619
  • 4
  • 21
  • 79
  • Is specifying each attribute necessary? Like, if I want Ctrl+S, do you need to specify that alt="UP"? – Stealth Rabbi Dec 29 '15 at 17:33
  • Hmm, I got a runtime error (when the view loads) if I do not specify all the attributes. I would think that defaults would be OK, but I guess not. – Stealth Rabbi Dec 29 '15 at 17:34
  • @UnKnown Mine are aligned right. If your's aren't, ask a question and add a screenshot and small sample or some details of your setup. – brian Jul 23 '16 at 23:31
  • @brian http://stackoverflow.com/questions/38545939/customize-javafx-menubar-to-remove-margin Here I asked. I want menu items same as Firefox have. – Asif Mushtaq Jul 24 '16 at 05:30
1

If your are not using fxml file then you can add key combination like below.

MenuItem gotoLine = new MenuItem("Goto");
KeyCombination gotoKeyCombination = new KeyCodeCombination(KeyCode.G, KeyCombination.CONTROL_DOWN);
gotoLine.setAccelerator(gotoKeyCombination);
gotoLine.setOnAction(event -> {
            System.out.println("CTRL+G event triggered");
            System.out.println(event.toString());
 });
gprasadr8
  • 789
  • 1
  • 8
  • 12