如何在 JPasswordField 中添加眼睛符号?

How to add eye symbol in JPasswordField?

如何使用 java swing 在我的 java 应用程序中添加眼睛符号?

您可以通过多种方式实现这一点。在下面的代码中,我创建了一个 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 MouseListenerJLabel。当鼠标指针在JLabel内时,JPasswordField内的文字可读,当鼠标指针不在[=12=内]时,显示JPasswordField内的文字作为星号字符的字符串,即 *.

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());
    }
}