If a scene has only shapes, requestFocus() must be used explicitly before being able to process keyboard events.
I tried it myself! See below.
SceneWithShapes.java

FXMLDocument.FXML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<?import javafx.scene.shape.*?> | |
<?import java.lang.*?> | |
<?import java.util.*?> | |
<?import javafx.scene.*?> | |
<?import javafx.scene.control.*?> | |
<?import javafx.scene.layout.*?> | |
<Group onKeyPressed="#keyHandler" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="scenewithshapes.FXMLDocumentController"> | |
<children> | |
<Sphere layoutX="50.0" layoutY="50.0" radius="50.0" /> | |
</children> | |
</Group> |
FXMLDocumentController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package scenewithshapes; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import static javafx.scene.input.KeyCode.A; import javafx.scene.input.KeyEvent; /** * * @author Cristina */ public class FXMLDocumentController implements Initializable { @Override public void initialize(URL url, ResourceBundle rb) { // TODO } public void keyHandler(KeyEvent event){ System.out.println("A Key was pressed"); } }
|