/* KeyboardInputDemoFX.java Copyright (c) Kari Laitinen http://www.naturalprogramming.com/ 2014-12-29 File created. 2014-12-29 Last modification. This program shows how a Java FX program can find out which keys are pressed on the keyboard. */ import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.text.* ; import javafx.scene.input.* ; // KeyEvent, KeyCode public class KeyboardInputDemoFX extends Application { Font large_font = Font.font( "SansSerif", FontWeight.BOLD, 24 ) ; KeyCode code_of_last_pressed_key = KeyCode.EXCLAMATION_MARK ; Group group_for_texts = new Group() ; Text main_text_line = new Text( 100, 200, "Last pressed key: ?" ) ; Text additional_text = new Text( 100, 250, "" ) ; private void set_text_lines() { main_text_line.setText( "Last pressed key: " + code_of_last_pressed_key.getName() ) ; // The KeyCode enum provides predefined constants (e.g. F1) // which can be used to refer to the individual keys on the keyboard. if ( code_of_last_pressed_key == KeyCode.F1 ) { additional_text.setText( "You pressed the F1 key" ) ; } else if ( code_of_last_pressed_key == KeyCode.UP ) { additional_text.setText( "You pressed the Arrow Up key" ) ; } else if ( code_of_last_pressed_key == KeyCode.DOWN ) { additional_text.setText( "You pressed the Arrow Down key" ) ; } else { additional_text.setText( "" ) ; } } public void start( Stage stage ) { stage.setTitle( "KeyboardInputDemoFX.java" ) ; Scene scene = new Scene( group_for_texts, 960, 720 ) ; scene.setFill( Color.SEASHELL ) ; // Light reddish color. main_text_line.setFont( large_font ) ; additional_text.setFont( large_font ) ; group_for_texts.getChildren().addAll( main_text_line, additional_text ) ; scene.setOnKeyPressed( ( KeyEvent event ) -> { code_of_last_pressed_key = event.getCode() ; set_text_lines() ; System.out.print( "\n KeyPressed. Key code = " + code_of_last_pressed_key ) ; } ) ; scene.setOnKeyReleased( ( KeyEvent event ) -> { System.out.print( "\n KeyReleased." ) ; } ) ; scene.setOnKeyTyped( ( KeyEvent event ) -> { // KeyTyped event occurs when a visible character is typed. // The Space character is considered visible. The pressing of the // Shift key does not produce a KeyTyped event. System.out.print( "\n KeyTyped. Character = " + event.getCharacter() ) ; } ) ; stage.setScene( scene ) ; stage.show() ; } public static void main( String[] command_line_parameters ) { launch( command_line_parameters ) ; } } /* NOTES: The following were useful pages when this program was developed: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/text/Text.html https://docs.oracle.com/javase/8/javafx/api/javafx/scene/text/Font.html https://docs.oracle.com/javase/8/javafx/api/javafx/scene/input/KeyCode.html https://docs.oracle.com/javase/8/javafx/api/javafx/scene/input/KeyEvent.html */