【问题标题】:Sending Textfield input on ButtonClick or Enter Key在按钮单击或输入键上发送文本字段输入
【发布时间】:2018-09-23 04:59:37
【问题描述】:

我正在尝试进行聊天,因此当我按下回车键或按下“发送”按钮时,文本字段的输入将进入 ListView。尽管代码确实很混乱,但它确实可以完成工作。

我的控制器代码如下:

public void initialize() {
        sendButton.setDisable(true);

}

public void isChatEmpty() {
    boolean isChatEmpty = textInput.getText().isEmpty();
    sendButton.setDisable(isChatEmpty);
}
public void sendMessageOnClick(){
    sendButton.setOnAction((e) -> {
        String message = textInput.getText();
        chatHistory.getItems().add("Sorin: " + message + "\n");
        textInput.setText(null);
        sendButton.setDisable(true);
    });
}
public void sendMessageOnEnter(){
    textInput.setOnKeyPressed(e -> {
        if (e.getCode() == KeyCode.ENTER) {
            String message = textInput.getText();
            chatHistory.getItems().add("Sorin: " + message + "\n");
            textInput.setText(null);
            sendButton.setDisable(true);
            System.out.print("test");
        }
    });
}

我知道它有效,因为我可以在 GUI 中看到它,但不知何故,我在我的“isChatEmpty”上获得了一个 Nullpointer,公平地说,我不知道为什么。

Caused by: java.lang.NullPointerException
    at sample.Controller.isChatEmpty(Controller.java:29)

另外,有没有办法结合这两个 Lambdas 函数?

提前谢谢你!

【问题讨论】:

    标签: java listview button javafx textinput


    【解决方案1】:

    在输入和单击的情况下,有一个简单的方法来处理这个问题:对两者都使用onAction 方法。对于TextField,这是在您按下回车时触发的。此外,应该从 fxml 分配这些处理程序。也可以使用绑定来禁用按钮:

    <TextField fx:id="textInput" onAction="#send"/>
    <Button fx:id="sendButton" text="Send" onAction="#send"/>
    
    @FXML
    private void initialize() {
        sendButton.disableProperty().bind(textInput.textProperty().isEmpty());
    }
    
    @FXML
    private void send() {
        String message = textInput.getText();
        if (message != null && !message.isEmpty()) {
            chatHistory.getItems().add("Sorin: " + message);
            textInput.clear();
        }
    }
    

    【讨论】:

      【解决方案2】:

      isChatEmpty() 方法中,textInput.getText() 的结果是null,正如您使用textInput.setText(null); 设置的那样。 这个 null 会导致 NPE(请参阅文档了解 String.isEmpty())。

      要解决此问题,您可以删除 isChatEmpty() 方法并设置单向绑定:

      public void initialize() {
          sendButton.disableProperty().bind(textInput.textProperty().isEmpty());
      }
      

      注意这里的.isEmpty() 不是对String.isEmpty() 的调用,而是对 StringExpression.isEmpty() 生成 BooleanBinding 类型的绑定。

      【讨论】:

      • 说得好!我现在把初始化方法替换了,也把isChatEmpty()删了,但是我得到了这个Exception in Application start method java.lang.reflect.InvocationTargetException你也看看我的第二个问题吗?
      • 我以某种方式修复了它,只是不使用textInput.setText(null),而只是使用textInput.clear(),令人惊讶的是,它使它起作用了:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      • 2015-09-11
      • 2016-05-15
      相关资源
      最近更新 更多