HCBPshenanigans HCBPshenanigans - 3 months ago 27
Java Question

JavaFX: How to make enter key submit TextArea

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

I am trying to make a bare bones chat client. I am using the JavaFX Scene builder to make the client UI, and a controller class connected to the FXML.

How can I make is so that the current text of in the text area is submitted to the server and the text area is cleared upon the enter key press, instead of using some kind of "send" button?

EDIT: Here is the code that is not working:

//...

public class FXMLDocumentController
{

//...

@FXML private TextArea messageBox;

//...

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

//...

Answer

This should get you 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("");
        }
    }
});

I might add, that if you are so inclined to provide both a button and an enter key event, you could tie the event handler functions of both controls to a single common function in a way such as this:

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("");
}

Either way works, good luck.