JavaFX系列 - 自定义密码输入框

JavaFX系列 - 自定义密码输入框

首页音乐舞蹈代号FX更新时间:2024-05-09

JavaFX默认的PasswordField控件不能动态切换输入内容是否可见,无法满足实际需求。这里通过自定义JavaFX控件,实现如下的效果:

隐藏密码时

显示密码时

实现思路代码

public class FXPasswordField extends StackPane { private final TextField textField; private final PasswordField passwordField; public FXPasswordField() { super(); textField = new TextField(); passwordField = new PasswordField(); initStyle(); initEvent(); textField.textProperty().bindBidirectional(passwordField.textProperty()); getChildren().addAll(textField, passwordField); } private void initStyle() { String style = "-fx-padding: 5px 30px 5px 5px; -fx-background-repeat: no-repeat; -fx-background-position: right 10 center; -fx-background-size: contain;"; String textFieldStyle = style "-fx-background-image: url(/assets/image/eye-open.png);"; String passwordFieldStyle = style "-fx-background-image: url(/assets/image/eye-close.png);"; textField.setStyle(textFieldStyle); passwordField.setStyle(passwordFieldStyle); setOnMouseMovedEvent(textField, textFieldStyle); setOnMouseMovedEvent(passwordField, passwordFieldStyle); } private void setOnMouseMovedEvent(TextField textField, String style){ textField.setOnMouseMoved((MouseEvent event) -> { double width = textField.getWidth(); if(event.getX() > width - 30){ textField.setStyle(style "-fx-cursor: hand;"); }else{ textField.setStyle(style "-fx-cursor: text;"); } }); } private void initEvent(){ setOnMouseClickedEvent(textField, passwordField); setOnMouseClickedEvent(passwordField, textField); } private void setOnMouseClickedEvent(TextField willHideInput, TextField willShowInput){ willHideInput.setOnMouseClicked((MouseEvent event) -> { double width = textField.getWidth(); if(event.getX() > width - 30){ // 移除当前显示的输入框, 显示另一个输入框 setNodeVisible(willHideInput, false); setNodeVisible(willShowInput, true); } }); } private void setNodeVisible(Node node, boolean visible){ node.setVisible(visible); node.setManaged(visible); } public String getText(){ return textField.getText(); } }使用

,
大家还看了
也许喜欢
更多游戏

Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved