Skip to content

Instantly share code, notes, and snippets.

@drguildo
Last active March 1, 2023 10:09
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save drguildo/ba2834bf52d624113041 to your computer and use it in GitHub Desktop.
Save drguildo/ba2834bf52d624113041 to your computer and use it in GitHub Desktop.
JavaFX doesn't have a password dialog, so I wrote one.
package io.sjm.diary;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
public class PasswordDialog extends Dialog<String> {
private PasswordField passwordField;
public PasswordDialog() {
setTitle("Password");
setHeaderText("Please enter your password.");
ButtonType passwordButtonType = new ButtonType("Decrypt", ButtonData.OK_DONE);
getDialogPane().getButtonTypes().addAll(passwordButtonType, ButtonType.CANCEL);
passwordField = new PasswordField();
passwordField.setPromptText("Password");
HBox hBox = new HBox();
hBox.getChildren().add(passwordField);
hBox.setPadding(new Insets(20));
HBox.setHgrow(passwordField, Priority.ALWAYS);
getDialogPane().setContent(hBox);
Platform.runLater(() -> passwordField.requestFocus());
setResultConverter(dialogButton -> {
if (dialogButton == passwordButtonType) {
return passwordField.getText();
}
return null;
});
}
public PasswordField getPasswordField() {
return passwordField;
}
}
@drguildo
Copy link
Author

Example usage:

import io.sjm.diary.PasswordDialog;

import java.util.Optional;

import javafx.application.Application;
import javafx.stage.Stage;

public class Test extends Application {
  @Override
  public void start(Stage stage) throws Exception {
    PasswordDialog pd = new PasswordDialog();
    Optional<String> result = pd.showAndWait();
    result.ifPresent(password -> System.out.println(password));
  }

  public static void main(String[] args) {
    launch(args);
  }
}

@williamsrn
Copy link

Works good. Thanks 👍

@xpathexception
Copy link

xpathexception commented May 22, 2017

This won't work if you are using custom button text (translations for example) and setting it after constructor. This can be fixed by simply changing

if (dialogButton == passwordButtonType) 

to

if (dialogButton.getButtonData() == passwordButtonType.getButtonData())

@cmaggiulli
Copy link

Awesome. Do you mind if I put this in a non commercial project I'm working on? I will give acknowledgement

@IbrokhimjonAkhmadjonov
Copy link

Thank you. It is very usefull for me!

@ubaid4j
Copy link

ubaid4j commented Mar 23, 2019

Thanks .....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment