This is my first time working with JavaFX, I tried to create a KeyListener (KeyTyped) that reacts to the whole scene, since I don't like to always click into textfields/areas etc.
So I got the following code:
package view;
import controller.Function;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class MainGame implements Initializable {
public TextField txtText;
protected String word = "ABC";
void start(ActionEvent event) throws IOException {
URL url = new File("src/main/java/view/MainGame.fxml").toURI().toURL();
Parent MainGame_parent = FXMLLoader.load(url);
Scene MainGame_scene = new Scene(MainGame_parent);
Stage primaryStage_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
primaryStage_stage.setScene(MainGame_scene);
primaryStage_stage.show();
MainGame_scene.addEventFilter(KeyEvent.KEY_TYPED, (KeyEvent ev) -> {
//System.out.println(Function.decrypt(word, txtText.getText(), ev.getCharacter().charAt(0)));
//txtText.setText(Function.decrypt(word, txtText.getText(), ev.getCharacter().charAt(0)));
//Function.won(word, txtText.getText());
});
}
@Override
public void initialize(URL url, ResourceBundle rb) {
txtText.setText(Function.encrypt(word));
}
}
Now, this code itself works, it just doesn't do anything if a key is pressed. The three comments would be responsible for that, but whenever I uncomment one or more, they cause a NullPointerException. I have already tried to print the different values. Every value worked except for txtText, which caused a NullPointerException.
I have tried moving it to different places, putting it into an own function, putting it into initialize, not declaring it in the class body but in the function and I also tried putting the rest of the start method in the constructor. Sadly none of those things worked.
I have no idea what to do and how to fix this. Thanks for any help!