Reputation: 83
i'm trying to build a JavaFX FXML Application and i have a TextField and i want when press Enter Key
and the cursor is in the TextField that key will do something... i traied this code it has a mistake i couldn't fix it :
@FXML
private void onKeyTyped (ActionEvent ee) {
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void keyt (KeyEvent evt) throws IOException{
//do something
}
});
}
So please help me and thanks :)
Upvotes: 0
Views: 851
Reputation: 2949
TextFiledEvent.class
public class TextFiledEvent extends Application {
@Override
public void start(Stage primaryStage) {
TerminalTextField btn = new TerminalTextField();
VBox root = new VBox();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
TerminalTextField.class
class TerminalTextField extends TextField {
ArrayList<String> arrayList = new ArrayList<>();
int sizeOfList = 10;
int keyPoint;
public TerminalTextField() {
setField();
}
public TerminalTextField(String text) {
super(text);
setField();
}
private void setField() {
setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode().isLetterKey()) {
setText(getText().toString().toUpperCase());
positionCaret(getLength());
}
}
});
}
}
Upvotes: 1
Reputation: 3333
You can achieve this by setting the fx id in scene builder of the fxml file of the text field. This should get rid of the need for the "private void onKeyTyped (ActionEvent ee) {" Then in the initialize method in your control class for example MainControl you need to add the set on key pressed with the event handler
Here is an example of how that would look:
package application;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
public class MainControl implements Initializable {
@FXML
TextField text1;
public void initialize(URL arg0, ResourceBundle arg1) {// Initializes
// everything
text1.setOnKeyPressed(new EventHandler<KeyEvent>() {// Keyboard // commands
public void handle(KeyEvent ke) {
if (ke.getCode().toString().equalsIgnoreCase("ENTER")) {
//do something
}
}
});
}
}
I hope that this helps
Upvotes: 1