java textarea 回车事件,JavaFX:如何使回车键提交TextArea

这应该可以满足您的需求:

TextArea area;

//... (initialize all your JavaFX objects here...)

// wherever you assign event handlers...

area.setOnKeyPressed(new EventHandler() {

@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() {

@Override

public void handle(ActionEvent actionEvent) {

sendFunction();

}

});

area.setOnKeyPressed(new EventHandler() {

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

}

无论哪种方式都有效,祝你好运 .

你可能感兴趣的:(java,textarea,回车事件)