Search code examples
javajavafxfxml

Run method in FXML Controller on KeyEvent


I have a function that updates a ListView in my FXML Controller Class. I want this to run every time the user presses F5.

I'm not sure what the best way is to achieve this and tried following:

1. Get the scene from the controller

I tried to get the scene like here and added scene.onKeyPressed(e -> ...);. But I failed to find a way to get the scene reliably.

2. Call the function from outside

Furthermore I tried to handle this from my scene controller, not my preferred way, because I don't want to call this method when this particular file is not loaded. I load the FXML file with layout.setCenter(FXMLLoader.load(...)); I failed to get an instance of the Controller itself, where I could call the method.

What is wrong with my design? Or is there an @FXML annotation that allows me to handle a KeyEvent?

Example

ApplicationManager:

@Override
public void start(Stage stage){
   BorderPane layout = new BorderPane();
   Scene scene = new Scene(layout);

   layout.setCenter(FXMLLoader.load(getClass().getResource("/designs/lobby.fxml");
}

LobbyFxmlController:

@FXML private ListView<Label> lobbyListView;

@FXML
public void initialize(){
    //I can't get the scene here
}

private void loadLobbies(){
    // I need to run this on F5 presses
    lobbyListView.setItems("lobby 1", "lobby 2", "lobby 3");
 }


Solution

  • I just needed to add onKeyPressed="#handleKeyPress" to the FXML layout item and handle this method in the Controller.