JavaFX TextField handle enter key pressed event

Introduction

TextField fires action events for the text field with when ENTER is pressed while the text field has input focus.


// Demonstrate a text field. 
 
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage; 
 
public class Main extends Application { 
 
  private TextField textField; 
  private Label response = new Label("Search String: "); 
 
  public static void main(String[] args) { 
    launch(args);   /*from  www.  j av  a  2s  .  c o m*/
  } 
  public void start(Stage myStage) { 
    myStage.setTitle("Demonstrate a TextField"); 
 
    // Use a FlowPane for the root node. In this case, 
    // vertical and horizontal gaps of 10. 
    FlowPane rootNode = new FlowPane(10, 10); 
    rootNode.setAlignment(Pos.CENTER); 
    Scene myScene = new Scene(rootNode, 230, 140); 
    myStage.setScene(myScene); 
 
    Button btnGetText = new Button("OK"); 
 
    // Create a text field 
    textField = new TextField(); 
 
    // Set the prompt. 
    textField.setPromptText("Enter Search String"); 
 
    // Set preferred column count. 
    textField.setPrefColumnCount(15); 
 
    textField.setOnAction(e->{ 
        response.setText("Search String: " + textField.getText()); 
    }); 
 
    // Get text from the text field when the button is pressed 
    btnGetText.setOnAction(e->{ 
        response.setText("Search String: " + textField.getText()); 
    }); 
 
    // Use a separator to better organize the layout. 
    Separator separator = new Separator(); 
    separator.setPrefWidth(180); 
 
    rootNode.getChildren().addAll(textField, btnGetText, separator, response); 
  
    myStage.show(); 
  } 
}



PreviousNext

Related