天天看點

Swing 給密碼框JPasswordField設定顯示和隐藏密碼功能

先上個效果圖

Swing 給密碼框JPasswordField設定顯示和隐藏密碼功能

 接下來代碼

JPasswordField pwd = new JPasswordField();
pwd.setEchoChar('*');

//添加顯示密碼圖示按鈕
JButton viewBtn = new JButton(new ImageIcon(Objects.requireNonNull(this.getClass().getClassLoader().getResource("view.png"))));

//添加隐藏密碼圖示按鈕
JButton viewHideBtn = new JButton(new ImageIcon(Objects.requireNonNull(this.getClass().getClassLoader().getResource("view_hide.png"))));

//将圖示按鈕添加進密碼框裡面,需要使用FlatLightLaf主題庫
//導入依賴後在所有swing元件的最前面(或者在方法一開始)添加 FlatLightLaf.setup(); 即可,maven位址放最下面了

//如果不需要将按鈕添加進框裡則無需使用FlatLightLaf,添加相應按鈕到面闆相應位置即可
pwd.putClientProperty("JTextField.trailingComponent", viewBtn);


//給顯示密碼圖示綁定單擊事件
viewBtn.addActionListener(new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent e) {
         pwd.putClientProperty("JTextField.trailingComponent", viewHideBtn);//設定隐藏按鈕顯示,未使用FlatLightLaf則不需要
         pwd.setEchoChar((char) 0);//設定密碼顯示
     }
});

//給隐藏密碼圖示綁定單擊事件
viewHideBtn.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {
           pwd.putClientProperty("JTextField.trailingComponent", viewBtn);//設定顯示按鈕顯示,未使用FlatLightLaf則不需要
           pwd.setEchoChar('*');//設定密碼隐藏
       }
});



//注:FlatLightLaf maven位址
<dependency>
	<groupId>com.formdev</groupId>
	<artifactId>flatlaf</artifactId>
	<version>2.4</version>
</dependency>

           

說明一下,如果沒有使用 FlatLightLaf,則在點選按鈕後設定另外一個按鈕顯示或隐藏即可

調用方法

btn.setVisible(false);      

可隐藏按鈕