JavaFX PasswordField将值从项目符号转换为文本字符

时间:2018-06-19 06:53:06

标签: java javafx

我只想在PasswordField设置为ToggleButton时显示TRUE的输入值,Bullets将转换为Text Character,非常简单。我找到了this,但不幸的是我因为com.sun.javafx.scene.control.behavior.PasswordFieldBehavior无法解决而存货。

通常情况下,我们如何或PasswordField如何将Bullets转换为Text Character?它有什么功能吗?

2 个答案:

答案 0 :(得分:4)

您可以堆叠另一个TextField并绑定它们的值。

final StackPane sp = new StackPane();
final PasswordField pwf = new PasswordField();
final TextField tf = new TextField();
final ToggleButton toggle = new ToggleButton();

sp.getChildren().addAll(pwf, tf);

pwf.textProperty().bindBidirectional(tf.textProperty());
pwf.visibleProperty().bind(toggle.selectedProperty().not());
tf.visibleProperty().bind(toggle.selectedProperty());

根据您对两个输入控件的大小调整策略的方式,您可能需要为文本字段调用#setManaged(false)

答案 1 :(得分:0)

你必须通过继承TextFieldSkin并在那里覆盖maskText(String txt)来编写自己的皮肤,以返回原始文本而不是子弹。

这是一个可执行的例子:

package application;

import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.skin.TextFieldSkin;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        HBox root = new HBox();

        PasswordField passwordField = new PasswordField();

        BooleanProperty showPassword = new SimpleBooleanProperty() {
            @Override
            protected void invalidated() {
                // force maskText to be called
                String txt = passwordField.getText();
                passwordField.setText(null);
                passwordField.setText(txt);
            }
        };

        passwordField.setSkin(new TextFieldSkin(passwordField) {
            @Override
            protected String maskText(String txt) {
                if (showPassword.get()) {
                    return txt;
                }
                return super.maskText(txt);
            }
        });

        ToggleButton bulletToggle = new ToggleButton("Show Password");
        showPassword.bind(bulletToggle.selectedProperty());

        root.getChildren().addAll(passwordField, bulletToggle);

        Scene scene = new Scene(root);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

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