JavaFX KeyCode check enter key
import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.text.Text; import javafx.scene.input.KeyCode; public class Main extends Application { @Override/*from w w w. j a va2 s.co m*/ public void start(Stage primaryStage) { final double WIDTH = 500.0; final double HEIGHT = 500.0; Pane pane = new Pane(); pane.setOnKeyPressed(e -> { pane.getChildren().clear(); if (e.getCode() == KeyCode.ENTER) { Text text = new Text(WIDTH / 4, HEIGHT / 2, "enter"); pane.getChildren().add(text); } else { Text text = new Text(WIDTH / 4, HEIGHT / 2, e.getCode().toString()); pane.getChildren().add(text); } }); Scene scene = new Scene(pane, WIDTH, HEIGHT); primaryStage.setTitle("java2s.com"); primaryStage.setScene(scene); primaryStage.show(); pane.requestFocus(); } public static void main(String[] args) { launch(args); } }
import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class Main extends Application { final double KILOMETERS_PER_MILE = 1.602307322544464; protected TextField tfMile = new TextField(); protected TextField tfKilometer = new TextField(); @Override/*from w ww . j a v a 2 s . c o m*/ public void start(Stage primaryStage) { // Set text fields alignment tfMile.setAlignment(Pos.BOTTOM_RIGHT); tfKilometer.setAlignment(Pos.BOTTOM_RIGHT); // Create a gridpane and place nodes into it GridPane pane = new GridPane(); pane.setAlignment(Pos.CENTER); pane.add(new Label("Mile"), 0, 0); pane.add(tfMile, 1, 0); pane.add(new Label("Kilometer"), 0, 1); pane.add(tfKilometer, 1, 1); // Create and register the handlers tfMile.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.ENTER && tfMile.getText().length() > 0) { double miles = Double.parseDouble(tfMile.getText()); tfKilometer.setText(String.valueOf(miles * KILOMETERS_PER_MILE)); } }); tfKilometer.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.ENTER && tfKilometer.getText().length() > 0) { double kilometers = Double.parseDouble(tfKilometer.getText()); tfMile.setText(String.valueOf(kilometers / KILOMETERS_PER_MILE)); } }); // Create a scene and place it in the stage Scene scene = new Scene(pane, 250, 60); primaryStage.setTitle("java2s.com"); primaryStage.setScene(scene); primaryStage.show(); } }