Java Program using JPasswordField with ActionListener


In this program, You will learn how to implement JPasswordField with ActionListener in java.


JPasswordField jp

public void actionPerformed(ActionEvent e) { 
   //statement
}

Example: How to implement JPasswordField with ActionListener in java.

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

class Test extends JFrame implements ActionListener {

    JButton jb1, jb2;
    JTextField jt1;
    JPasswordField jp;
    JLabel lbl;

    Test() {

        jt1 = new JTextField();
        jt1.setBounds(90, 50, 150, 30);
        add(jt1);

        jp = new JPasswordField();
        jp.setBounds(90, 80, 150, 30);
        add(jp);

        lbl = new JLabel("Result :");
        lbl.setBounds(90, 140, 150, 30);
        add(lbl);

        jb1 = new JButton("+");
        jb1.setBounds(50, 200, 100, 30);
        add(jb1);

        jb2 = new JButton("-");
        jb2.setBounds(180, 200, 100, 30);
        add(jb2);

        jb1.addActionListener(this);
        jb2.addActionListener(this);

        setLayout(null);
        setSize(600, 400);
        setVisible(true);

    }

    public void actionPerformed(ActionEvent e) {

        int a = Integer.parseInt(jt1.getText());
        int b = Integer.parseInt(jp.getText());
        int c = 0;

        if (e.getSource().equals(jb1)) {
            c = a + b;
            lbl.setText(String.valueOf(c));
        } else if (e.getSource().equals(jb2)) {
            c = a - b;
            lbl.setText(String.valueOf(c));
        }
    }

    public static void main(String args[]) {
        Test t = new Test();
    }
}

Output:

JPasswordField