JavaFX密码字段

PasswordField用于密码输入。用户键入的字符通过显示回显字符串被隐藏。

创建密码字段

以下代码使用来自PasswordField类的默认构造函数创建一个密码字段,然后为密码字段设置提示消息文本。 提示消息在字段中显示为灰色文本,并为用户提供该字段是什么的提示,而不使用标签控件。

PasswordField passwordField = new PasswordField();
passwordField.setPromptText("Your password");

Java

PasswordField类有setText方法来为控件设置文本字符串。对于密码字段,指定的字符串由回显字符隐藏。默认情况下,回显字符是一个点(或是星号)。

密码字段中的值可以通过getText()方法获取。

示例

密码字段和操作侦听器,如下所示 -

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {

  final Label message = new Label("");

  @Override
  public void start(Stage stage) {
    Group root = new Group();
    Scene scene = new Scene(root, 260, 80);
    stage.setScene(scene);
    stage.setTitle("Password Field Sample");

    VBox vb = new VBox();
    vb.setPadding(new Insets(10, 0, 0, 10));
    vb.setSpacing(10);
    HBox hb = new HBox();
    hb.setSpacing(10);
    hb.setAlignment(Pos.CENTER_LEFT);

    Label label = new Label("Password");
    final PasswordField pb = new PasswordField();

    pb.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent e) {
        if (!pb.getText().equals("abc")) {
          message.setText("Your password is incorrect!");
          message.setTextFill(Color.web("red"));
        } else {
          message.setText("Your password has been confirmed");
          message.setTextFill(Color.web("black"));
        }
        pb.setText("");
      }
    });

    hb.getChildren().addAll(label, pb);
    vb.getChildren().addAll(hb, message);

    scene.setRoot(vb);
    stage.show();
  }

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

Java

上面的代码生成以下结果。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧浩海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值