如何使用 java swing 在我的 java 應用程式中添加眼睛符號?
uj5u.com熱心網友回復:
您可以通過多種方式實作這一點。在下面的代碼中,我創建了一個JPanel,其中包含一個JPasswordField和一個顯示“眼睛”圖示的JLabel 。我從JPasswordField. _ (請注意,默認情況下, aJLabel沒有邊框。)我添加了一個邊框JPanel,使它看起來像一個單獨的文本欄位。我從接受的答案中得到了這個想法How to put a JButton inside a JTextField (Java)。最后,我將MouseListener添加到JLabel. 當滑鼠指標在 里面時JLabel,里面的文字JPasswordField是可讀的,當滑鼠指標不在里面時JLabel,里面的文字是可讀的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());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/475243.html
