JavaFX: how to make submit key enter TextArea

Sorry if this seems too easy, I'm brand new to JavaFX, this is my first little application built with it.

I am trying to make a bare bone chat client. I use the JavaFX Scene builder to make the client user interface, and the controller class connected to FXML.

How can I make sure that the current text in the text area is sent to the server and the text area is deleted when I press the enter key, instead of using any send button?

EDIT: Here is the code that does not work:

//...

public class FXMLDocumentController
{

//...

@FXML private TextArea messageBox;

//...

messageBox.setOnKeyPressed(new EventHandler<KeyEvent>() 
{
    @Override
    public void handle(KeyEvent keyEvent) 
    {
        if(keyEvent.getCode() == KeyCode.ENTER)
        {
            //sendMessage();
        }
    }
});

//...
+4
source share
2 answers

This should get what you want:

TextArea area;
//... (initialize all your JavaFX objects here...)

// wherever you assign event handlers...
area.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent keyEvent) {
        if (keyEvent.getCode() == KeyCode.ENTER)  {
            String text = area.getText();

            // do your thing...

            // clear text
            area.setText("");
        }
    }
});

, , , , :

Button sendButton;
TextArea area;
// init...

// set handlers
sendButton.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent actionEvent) {
         sendFunction();
    }
});

area.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent keyEvent) {
        if (keyEvent.getCode() == KeyCode.ENTER)  {
             sendFunction();
        }
    }
});

// define send function
public void sendFunction() {
    String text = this.area.getText();

    // do the send stuff

    // clear text (you may or may not want to do this here)
    this.area.setText("");
}

, .

+8

-... ,

textArea.setOnKeyPressed(event -> {
   if(event.getCode() == KeyCode.ENTER){
     //type here what you want
   }
}); 
+5

All Articles