Tutorial : How to Setup Key Combinations in JavaFX

At IDRSolutions we are currently in the process of Developing a JavaFX implementation of our PDFViewer. In previous JavaFX articles I have shown How to Create Stacked Menus in JavaFX and How to Create a Border Glow Effect in JavaFX. In this tutorial I will be showing you how to setup and chain key combinations/keyboard shortcuts in JavaFX. 

We will be learning how to use the keys Cntrl + E to call a MenuItem Accelerator which will exit the application and Cntrl + C which will set the style of a Text Object. By the end of this tutorial you should have a solid understanding of how to setup your own Key Combinations and time them to an accelerator in JavaFX.

 

Code in the Text

I will assume you have a basic understanding of JavaFX and how to setup and add to a Stage. Firstly we will create some text and pin it to the center of a BorderPane.

/**
* Create the Text.
*/
BorderPane root = new BorderPane();
Text text = new Text("BEFORE");
root.setCenter(text);

 

Code in the Main Menu

We need to create some MenuItem objects to tie key accelerators/combinations to them, however MenuItems need a Menu to contain them and a Menu has to be added to a MenuBar for our main menu to appear at the top of our application, so lets code them in.

/**
* Create a Menu.
*/
MenuBar menuBar = new MenuBar();
Menu mainMenu = new Menu("File");
MenuItem exitCmd = new MenuItem("Exit");
MenuItem textCmd = new MenuItem("Colour Text");
mainMenu.getItems().addAll(textCmd, exitCmd);
root.setTop(menuBar);

 

Code in the Listeners

We now want to add some MenuItem event handlers which will be triggered by our Key Combinations, lets code them in.

/**
* Setup MenuItem Listeners.
*/
//Handler to exit the application
exitCmd.setOnAction(new EventHandler() {
   @Override public void handle(ActionEvent e) {
      primaryStage.close();
   }
});
//Handler to style the text
textCmd.setOnAction(new EventHandler() {
   @Override public void handle(ActionEvent e) {
      text.setFill(Color.BLUE);
      text.setText("AFTER");
      text.setFont(Font.font("SansSerif", FontWeight.NORMAL,24));
   }
});

 

Code in the Key Combinations

Lastly, we will add our Key Combinations, when we press Cntrl + E it will Exit the application and when we press Cntrl + C it will style our text (Change the Colour and Font).

/**
* Setup KeyCombinations.
*/
exitCmd.setAccelerator(new KeyCodeCombination(KeyCode.E, KeyCombination.CONTROL_DOWN));
textCmd.setAccelerator(new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_DOWN));

 

End Result

If you have followed this tutorial correctly then see bellow for some before and after shots of using the Cntrl + C Key Combination, you should see something similar.

beforeafter

With some hope you can now add your own Key Combinations to your JavaFX Applications and have learnt something new! Please let us know below if you have anything to add or wish to leave a comment.

For the the code/class we have written in this tutorial please see here : keyCombDemo

You may find some of my other JavaFX articles of interest :
How to Create Stacked Menus in JavaFX
How to Create a Border Glow Effect in JavaFX.

We also have a JavaFX PDF Viewer plugin for NetBeans which you can grab here.

This post is part of our “JavaFX article Index” series. In these articles, we aim to explore the world of Java and Javafx. Have a look through!

If you’re a first-time reader, or simply want to be notified when we post new articles and updates, you can keep up to date by social media (TwitterFacebook and Google+) or the Blog RSS.

Related Posts:

The following two tabs change content below.
Nathan is a developer at IDRSolutions, focusing mainly on the development of HTML5 and Form support for the online PDF converter. He was a speaker and exhibitor at JavaOne 2013, co-presenting a session titled 'Lessons Learned from Using GlassFish with NetBeans". Nathan also enjoys writing technical blog-articles.
Nathan

About Nathan Howard

Nathan is a developer at IDRSolutions, focusing mainly on the development of HTML5 and Form support for the online PDF converter. He was a speaker and exhibitor at JavaOne 2013, co-presenting a session titled ‘Lessons Learned from Using GlassFish with NetBeans”. Nathan also enjoys writing technical blog-articles.

6 thoughts on “Tutorial : How to Setup Key Combinations in JavaFX

  1. […] of our PDFViewer. In previous JavaFX articles I have shown How to Create Stacked Menus, How to Setup Key Combinations and How to Create a Border Glow Effect all in […]

  2. Virgo47

    Helpful, but I got stuck on menu for a while – it didn’t want to appear. 🙂 Something like menuBar.getMenus().add(mainMenu) is missing – luckily easy to find in your other post you referenced. Here you name Menu “mainMenu”, in the referenced article “mainMenu” is name for the MenuBar – it also could have been consistent. Still you got me on track, thank you. 🙂

  3. NARESH

    After calling setHtmlText() can we set the cursor at last selection?

  4. Swapnil

    Shortcut does not work when focus is on text field… What to do?
    Please help me…

  5. alhelal

    Thank you. This helped me. You can explain the following line because understanding this one taking extra time to me(mainly KeyCombination.CONTROL_DOWN).
    textCmd.setAccelerator(new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_DOWN));

    You can add
    textCmd.setAccelerator(new KeyCodeCombination(KeyCode.C, KeyCombination.SHIFT_DOWN)); and can tell for this the shortkey is “shift + C”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>