Reputation: 127
I am currently working on an instant messaging program and have created a text for the user to enter a message in the FXML.
How do I add a KeyEvent
for when enter is pressed while the text field has focus.
Update - Tried, but doesn't work
<TextArea fx:id="area_chatInput"
editable="true"
prefHeight="60"
prefWidth="300"
wrapText="true"
promptText="Enter Message />
@FXML
private void keyListener(KeyEvent event){
if(event.getCode() == KeyCode.ENTER){
System.out.println("enter pressed");
sendMsg();
event.consume();
}
}
Upvotes: 0
Views: 4636
Reputation: 36772
You can add onKeyPressed
event listener to your TextField
in the fxml
.
...
<TextField fx:id="chatText" layoutX="199.0" layoutY="174.0" onKeyPressed="#keyListener" />
...
In the controller, declare a method keyListener
public void keyListener(KeyEvent event){
if(event.getCode() == KeyCode.ENTER) {
// Do stuff
((TextField)event.getSource()).clear(); // clear textfield
System.out.println("Enter Pressed"); // print a message
}
}
Update - According to comments
To avoid the cursor step to next line, you need to consume the event, before it leaves the method.
...
if (event.getCode() == KeyCode.ENTER) {
...
event.consume(); // Consume Event
}
...
Upvotes: 2