java jpasswordfield getpassword code example

Example: java jpasswordfield getpassword

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class Frame extends JFrame implements ActionListener{
 
    private JPasswordField jpf;
    private JTextField jtf;
    private JButton jb;
    private String name = "",pass = "";
    private char getpass[];

    Frame()
    {
        setTitle("JPasswordField with ActionListener");
        setLayout(new FlowLayout());
        setJTextFieldandJPasswordField();
        setAction();
        setSize(700, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    private void setJTextFieldandJPasswordField()
    {
        JLabel     username = new JLabel("User name");
        jtf = new JTextField("User name",10);
        JLabel     password = new JLabel("Password");
        jpf = new JPasswordField(10);
        jb = new JButton("Enter");
        JLabel     nameAndPass = new JLabel("User name  :  HAJSOF    Password  :  123456");
        add(username);
        add(jtf);
        add(password);
        add(jpf);
        add(jb);
        add(nameAndPass);
    }
 
    private void setAction()
    {
        jb.addActionListener(this);
    }
 
    public void actionPerformed(ActionEvent eve)
    {
        name = jtf.getText();
        getpass = jpf.getPassword();
        pass = String.valueOf(getpass);
     
        if(name.equals("HAJSOF") && pass.equals("123456"))
            JOptionPane.showMessageDialog(rootPane, "Login Successful");
        else
            JOptionPane.showMessageDialog(rootPane, "Username or Password incorrect");
    }
}

public class Javaapp {
 
    public static void main(String[] args) {
     
        Frame frame = new Frame();
    }
}

Tags:

Java Example