Home > Software design >  How to add eye symbol in JPasswordField?
How to add eye symbol in JPasswordField?

Time:05-15

How can I add an eye symbol in my java application using java swing?

CodePudding user response:

You can implement this several ways. In the below code, I create a JPanel which contains a JPasswordField and a JLabel which displays an "eye" icon. I remove the border from the JPasswordField. (Note that, by default, a JLabel does not have a border.) And I add a border to the JPanel that makes it look like a single, text field. I got that idea from the accepted answer to How to put a JButton inside a JTextField (Java). Finally, I add a MouseListener to the JLabel. When the mouse pointer is inside the JLabel, the text in the JPasswordField is readable and when the mouse pointer is not inside the JLabel, the text in the JPasswordField is displayed as a string of asterisk characters, i.e. *.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.border.BevelBorder;

public class PassWord extends MouseAdapter {
    private JFrame frame;
    private JPasswordField  passwordField;

    public void mouseEntered(MouseEvent event) {
        passwordField.setEchoChar('\u0000');
    }

    public void mouseExited(MouseEvent event) {
        passwordField.setEchoChar('*');
    }

    private void buildAndDisplayGui() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createEye(), BorderLayout.PAGE_START);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createEye() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
        panel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
        passwordField = new JPasswordField(15);
        passwordField.setBorder(null);
        panel.add(passwordField);
        URL location = getClass().getResource("eye_show_password.png");
        Icon ico = new ImageIcon(location);
        JLabel label = new JLabel(ico);
        label.setOpaque(true);
        label.setBackground(passwordField.getBackground());
        label.addMouseListener(this);
        panel.add(label);
        JPanel container = new JPanel();
        container.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        container.add(panel);
        return container;
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(() -> new PassWord().buildAndDisplayGui());
    }
}
  • Related