Saturday, 9 June 2018

JavaFX: Processing text field data

TextField class provides getText and setText methods to process text field data.

Find the below login form example. Enter user name and password fields in the login form and click on the SignIn button, you can able to see the entered values in console.

LoginForm.java
package com.sample.demos;

import java.io.FileNotFoundException;
import java.net.MalformedURLException;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class LoginForm extends Application {

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException, MalformedURLException {
  GridPane grid = new GridPane();
  grid.setPadding(new Insets(10, 10, 10, 10));
  grid.setVgap(5);
  grid.setHgap(5);

  TextField userName = new TextField();
  userName.setPromptText("Enter your name");
  GridPane.setConstraints(userName, 0, 0);
  grid.getChildren().add(userName);

  TextField password = new TextField();
  password.setPromptText("Enter password");
  GridPane.setConstraints(password, 0, 1);
  grid.getChildren().add(password);

  Button button = new Button("SignIn");
  Button clear = new Button("Clear");

  HBox hBox = new HBox(10, button, clear);

  button.setOnAction(event -> {
   String name = userName.getText();
   String pwd = password.getText();

   System.out.println("User Name : " + name);
   System.out.println("password : " + pwd);

  });

  clear.setOnAction(event -> {
   userName.setText("");
   password.setText("");
  });

  GridPane.setConstraints(hBox, 0, 2);
  grid.getChildren().add(hBox);

  Scene scene = new Scene(grid, 500, 300);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Form Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(LoginForm.class, args);
 }
}





Previous                                                 Next                                                 Home

No comments:

Post a Comment