JAVA - How To Set And Reset The Password Char Of A JPasswordField In Java Using JCheckBox

How To Set And Reset The Password Char Of A JPasswordField In Java

                                                                                            


Source Code:


package JavaDB_001;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;


public class Project extends JFrame{ 
    JCheckBox cb;
    public Project(){
    super("See And Hide JPasswordField Text");
    
    JPasswordField tf = new JPasswordField(60);
    tf.setEchoChar('*');
    tf.setBounds(80,20,250,20);
    
    cb = new JCheckBox("See Password");
    cb.setBounds(100,60,150,20);
    
    cb.addActionListener(new ActionListener(){
  
        public void actionPerformed(ActionEvent e) {              
          if(cb.isSelected()){
              //when JCheckBox is checked you can see the password
              tf.setEchoChar((char)0);
              //change the JCheckBox text
              cb.setText("Hide Password");
          }
          else{
              //when JCheckBox is unchecked you can't see the password
              tf.setEchoChar('*');
              //change the JCheckBox text
              cb.setText("See Password");
          }
        }
    });
    
   
    
    add(cb);
    add(tf);
    setLayout(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setSize(400,200);
    setVisible(true);
    }
    public static void main(String[] args){
        new Project();
    }
   }
////////////////////////////OUTPUT:

when JCheckBox is unchecked you can't see the password
Hide The Password In Java

when JCheckBox is checked you can see the password
See The Password In Java




Share this

Related Posts

Previous
Next Post »