2016-11-13 103 views
0

在一個javaFY項目中,我想將一個按下按鍵的監聽器添加到整個窗口中。在窗口的FXML文件的根節點是:按鍵事件未被觸發

<VBox onKeyPressed="#windowKeyPressed" fx:controller="hu.kleni.tetris.EventController" ...> 

而且興田事件處理類:

public class EventController { 
    @FXML 
    public void windowKeyPressed(KeyEvent event) { 
     System.out.println(event.getCode()); 
    } 
    ... 
} 

main()方法,它只是加載和啓動窗口。如果我啓動程序,窗口顯示出來,但按下一個鍵後,我看不到控制檯中的任何東西。我錯過了什麼?

編輯:雖然我可以用這個(它工作正常):

scene.setOnKeyPressed((event) -> { 
    // maybe call EventController.windowKeyPressed(event); 
}) 

,我更願意定義只有FXML文件中的所有事件處理程序。

回答

1

您需要rootVBox)才能讓onKeyPressed工作。

在你Application類,requestFocus()root顯示在Stage之後,例如:

@Override 
public void start(Stage stage) throws Exception { 
    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));   
    Scene scene = new Scene(root); 
    stage.setScene(scene); 
    stage.show(); 
    root.requestFocus(); // add this, root is the VBox in your case 
}