I recently started playing around with Java FX, FXML, and scene builder, and I've been trying to add key listeners to one of the controllers for a scene. When I do this though, the key listeners don't work as they should, and I figure it's because they're not focused onto that particular scene. I tried to get access to the scene the controller was part of in order to set it directly, but it comes up that it's part of a null scene.
Is there a way to gain access to the scene that this controller is used in in order to try and assign key event and listeners to that particular scene? Should I go through the rootController which is static throughout the whole application? Or, better yet, is there a simpler way of going about this?
Most examples I see assume that everything is mostly together in a main class or separated amongst a couple of other classes without FXML being brought in, and I'm not sure how to apply their fixes when I have the java controllers, FXML pages, and the main application all separated.
Thanks for any help!
Use any of the controls that is bound in the Controller and use getScene()
on it.
Remember not to use it in initialize()
as the root element(though completely processed) is still not placed on the scene when initialize()
is called for the controller
public class WindowMainController implements Initializable {
@FXML
private Button button;
@FXML
private void handleButtonAction(ActionEvent event) {
System.out.println(button.getScene()); // Gives you the Scene
}
@Override
public void initialize(URL url, ResourceBundle rb) {
System.out.println(button.getScene()); // Prints null
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With