DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Neil Ghosh Graduated from University College of Engineering, Burla and have over 6 years of experience in ERP, Web services and Web application development.He has contributed to various Financial Software and Mobile projects with his expertise in Oracle, Java, J2EE, jQuery, PHP and MySQL. Neil presently works for Electronic Arts and earlier worked as a project leader in Oracle Corporation in Oracle Applications ERP Development team. He is also chair of IEEE GOLD affinity group of Hyderabad section. He is also a co-organizer of Java User groups Hyderabad. Apart from programming his interest involves Astronomy and Cricket and other outdoor activities. Neil has posted 2 posts at DZone. You can read more from them at their website. View Full User Profile

Handling Keyboard Sortcuts in JavaFx

06.27.2013
| 7240 views |
  • submit to reddit
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
 public void handle(final KeyEvent keyEvent) {
   if (keyEvent.getCode() == KeyCode.F5) {
    System.out.println("F5 pressed");
    //Stop letting it do anything else
    keyEvent.consume();
   }
 }
});


final KeyCombination keyComb1 = new KeyCodeCombination(KeyCode.R,
                                    KeyCombination.CONTROL_DOWN);
scene.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
                @Override
                public void handle(KeyEvent event) {
                    if (keyComb1.match(event)) {
                        System.out.println("Ctrl+R pressed");
 
                    }
                }
            });

A lot of times you need to to assign some functionality to some keyboard shortcut like F5 or Ctrl+R  in your application. JavaFx also provides KeyCodeCombination API for handling multiple key events.