The method setOnKeyPressed on the scene is used to listen for key presses.
The key code is printed in the label.
package ex30;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class Ex30 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
Label label = new Label(" Press a key");
label.setFont(new Font("Georgia", 32));
root.getChildren().add(label);
Scene scene = new Scene(root, 500, 200, Color.GAINSBORO);
scene.setOnKeyPressed(e ->
label.setText(" Key Pressed: " +
e.getCode().toString()));
primaryStage.setScene(scene);
primaryStage.setTitle("Example 30. Keys");
primaryStage.show();
}
}
This is the output after a semicolon is pressed:
No comments:
Post a Comment