JavaFX - PasswordField



The text field accepts and displays the text. Using this we can accept input from the user and read it to our application. Similar to the text field, a password field accepts text but instead of displaying the given text, it hides the typed characters by displaying an echo string as shown in the below figure −

JavaFX passwordfield

PasswordField in JavaFX

In JavaFX, the class named PasswordField represents a password field which is belongs to the javafx.scene.control package. Using this we can accept input from the user and read it to our application. This class inherits the Text class. To create a password field, we need to instantiate this class by using the below constructor −

  • PasswordField() − This is the default constructor which will create an empty password field.

While creating a password field in JavaFX, our first step would be instantiating the PasswordField class by using its default constructor. Next, define a layout pane, such as Vbox or Hbox by passing the PasswordField object to its constructor. Lastly, set the scene and stage to display the password field on the screen.

Example

The following JavaFX program demonstrates how to create a password field in JavaFX application. Save this code in a file with the name JavafxPsswrdfld.java.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavafxPsswrdfld extends Application {
   public void start(Stage stage) {
      //Creating nodes
      TextField textField = new TextField();
      PasswordField pwdField = new PasswordField();
      //Creating labels
      Label label1 = new Label("Name: ");
      Label label2 = new Label("Pass word: ");
      //Adding labels for nodes
      HBox box = new HBox(5);
      box.setPadding(new Insets(25, 5 , 5, 50));
      box.getChildren().addAll(label1, textField, label2, pwdField);
      //Setting the stage
      Scene scene = new Scene(box, 595, 150, Color.BEIGE);
      stage.setTitle("Password Field Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

To compile and execute the saved Java file from the command prompt, use the following commands −

javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxPsswrdfld.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxPsswrdfld

Output

When we execute the above code, it will generate the following output.

Password Field Output
Advertisements