0

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");
 }

Lukas
  • 397
  • 6
  • 21
  • 2
    [mcve] please .. and make sure you have worked through a tutorial on how to use fxml (each and every one comes with an explanation of how to attach event handlers ;) – kleopatra Apr 17 '21 at 15:49
  • On a Button I would add `onAction="#handlerMethod"` in the fxml file (and a corresponding method in the controller). But I want this on key presses in this view, what would be the correct action for this, and where would I put it? Okay I answered my quastion there, sorry haha. I need to use `onKeyPressed` in the parent object in the FXML file. – Lukas Apr 17 '21 at 16:01

1 Answers1

0

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

Lukas
  • 397
  • 6
  • 21