Monday, August 11, 2014

JPasswordField usage

This sample program demonstrates the usage of JPasswordField:


import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import static net.mindview.util.SwingConsole.*;

public class Password extends JFrame{
    JPasswordField jpf = new JPasswordField("Enter password: ", 1);
    JButton button = new JButton("Submit");
    private String pass = "MYPASSWORD";
    
    ActionListener listen = new ActionListener(){
        @Override
            public void actionPerformed(ActionEvent e) {
                String userPass = new String(jpf.getPassword());
                if(userPass.matches(pass)){
                    JOptionPane.showMessageDialog(null, "Correct Password.");
                }else{
                    JOptionPane.showMessageDialog(null, "Incorrect Password.");
                    jpf.setText("");
                }
            }
    };
    
    Password(){ 
        setTitle("Enter password");
        jpf.setText("");
        jpf.addActionListener(listen);
        button.addActionListener(listen);
        
        jpf.setBorder(BorderFactory.createLoweredBevelBorder());
        button.setBorder(BorderFactory.createEtchedBorder());
        
        add(jpf);
        add(button, BorderLayout.SOUTH);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 150);
        setVisible(true);
        
    }
    public static void main(String[] args){
        Password ex = new Password(); 
    }
}


No comments:

Post a Comment