首页 > 解决方案 > 失去对我的事件处理函数中所有内容的引用

问题描述

我的想法:我想要一个用户可以输入命令的文本字段。他所有的输入都应该保存在一个列表中,作为一种历史,用户可以用他的箭头键滚动浏览它们。

我的问题:我多次调试我的代码,命令被适当地添加到历史记录(textarea)和列表中,但在我的事件处理程序中,对我的 textarea、textfield 和列表的所有引用始终为空。

我的代码:

public class Controller extends Application implements Initializable {

@FXML
private TextField commandInput;
@FXML
private TextArea commandHistory;

private LinkedList<String> commandList = new LinkedList<>();


@Override
public void start(Stage primaryStage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("layout.fxml"));
    primaryStage.setTitle("Airport");
    Scene scene = new Scene(root, 700, 275);
    primaryStage.setScene(scene);
    primaryStage.show();

    scene.addEventFilter(KeyEvent.KEY_PRESSED, event -> {

        if (!commandList.isEmpty()) {


            switch (event.getCode()) {
                case UP:
                    commandInput.setText(commandList.getFirst());
                    commandList.addLast(commandList.getFirst());
                    commandList.removeFirst();
                    break;

                case DOWN:
                    commandInput.setText(commandList.getLast());
                    commandList.addFirst(commandList.getLast());
                    commandList.removeLast();
                    break;
            }
        }
        System.out.println("Pressed: " + event.getCode());

    });
}

private boolean parseString(String input) {

    //TODO: Write Parser
    return true;
}

public void enterPressed(ActionEvent actionEvent) {
    String input = commandInput.getText();

    if (parseString(input)) {
        addCommandToHistory(input);
        commandList.add(input);
        System.out.println(commandList.getFirst());
        commandInput.setText("");
    } else {
        addCommandToHistory("input is no command");
    }

标签: eventsjavafxreferenceevent-handling

解决方案


推荐阅读