在JPasswordField

时间:2017-07-23 20:19:14

标签: java jframe jpasswordfield

我正在开发一个使用Java的系统(使用NetBeans),为了使它更具有专业性,我添加了一些很酷的功能,例如占位符(是的,我知道,它来自HTML)。

对于我所拥有的所有 JTextField ,我已使用以下代码生成其占位符(此示例中的JTextField的名称为" tfUser") :

private void tfUserFocusGained(java.awt.event.FocusEvent evt) {
    if (tfUser.getText().equals("Your User Name...")) {
        tfUser.setText("");
        tfUser.setForeground(Color.BLACK);
    }
}

private void tfUserFocusLost(java.awt.event.FocusEvent evt) {                                    
    if (tfUser.getText().equals("")) {
        tfUser.setText("Your User Name...");
        tfUser.setForeground(Color.GRAY);
    }
}

这是一场重点比赛": 文本字段最初包含文本"您的用户名...",其中包含"灰色"前景。每次此文本字段获得焦点时,它都会验证其文本:如果text.equals("您的用户名..."),其文本设置为"" (空字符串),Foreground设置为BLACK(默认值)。另一方面,如果text.equals(" Anything else ..."),则表示用户可能已插入用户名,因此,请勿对此代码执行任何操作。

每次文本字段失去焦点时,它都会验证其文本:如果text.equals("")(再次为空字符串),则其文本设置回"您的用户名..."并且前景设置为灰色。再次,如果text.equals(" Anything else ..."),则表示用户可能已插入用户名,因此,请勿对此代码执行任何操作。

此代码与JTextFields 完美配合,当我对 JPasswordFields 执行相同操作时,我得到以下结果:

****************  

(应该是"您的密码......")

有人可以帮我添加占位符到这个JPasswordField吗?提前谢谢。

1 个答案:

答案 0 :(得分:2)

我为登录代码所做的是添加一个“显示密码”的复选框,并在 jframe 中添加了以下语句:

//Setting checkbox selected to true so the word "password" is seen when program runs
 passCheckBox.setSelected(true);
    if(passCheckBox.isSelected())
    {
        PasswordField.setEchoChar((char)0);
    }`

密码复选框代码:

if(passCheckBox.isSelected())
        {
            PasswordField.setEchoChar((char)0);
        }else{
            
            PasswordField.setEchoChar('*');
        }

获得密码字段焦点代码:

private void PasswordFieldFocusGained(java.awt.event.FocusEvent evt) {                                          
    passCheckBox.setSelected(false);
    PasswordField.setEchoChar('*');
    String password = String.valueOf(PasswordField.getPassword());
    
    if(password.toLowerCase().equals("password"))
    {
        PasswordField.setText("");
        PasswordField.setForeground(Color.black);
    }
    
}     

 

密码字段焦点丢失的代码:

private void PasswordFieldFocusLost(java.awt.event.FocusEvent evt) {                                        
     
    String password = String.valueOf(PasswordField.getPassword());
    
    
    if(password.toLowerCase().equals("password") || password.toLowerCase().equals("") )
    {
        PasswordField.setText("Password");
        PasswordField.setEchoChar((char)0);
        PasswordField.setForeground(new Color(153, 153, 153));
    }
}                

我自己做了一半,并从视频中提取了一些内容,希望对您有所帮助:>