JPasswordField密碼框組件,其實跟JTextField文本框組件的使用非常相似,只不過多了一個回顯字符而已。
JPasswordField類所在包
JPasswordField類的所在包不用說大家都知道是javax.swing包了,所以開頭導入。
import javax.swing.*;
JPasswordField類構造方法
public JPasswordField();
public JPasswordField(String text);
public JPasswordField(int fieldwidth);
public JPasswordField(String text, int fieldwidth);
主要的構造方法就這些,這里簡單說一下text就是密碼框中的初始密碼,fieldwidth就是密碼框的寬度。
JPasswordField類使用方法
其實我認為JPasswordField類最主要的方法就是下面這個設置回顯字符的方法了。其中的字符c就是回顯字符。這里默認回顯字符是一個點。
password_field.setEchoChar(c);
剩下的大部分方法就幾乎和JTextField類完全一樣了,就是在獲取文本上有一點點區別,JPasswordField類獲取的是密碼,所以翻譯成英文就是getPassword。但這里務必注意該方法返回的是一個char類型的數組,所以得用String類型的構造方法將其轉換為字符串,代碼如下。
new String(password_field.getPassword());
代碼
package technology;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFirstJPasswordField extends JFrame {
final static long serialVersionUID = 1L;
Container container = getContentPane();
JLabel label = new JLabel("請輸入你的密碼:");
JPanel panel_north = new JPanel(), panel_center = new JPanel(), panel_south = new JPanel();
JButton button = new JButton("確認");
JPasswordField password_field = new JPasswordField("000000", 20);
class MyDialog extends JDialog {
final static long serialVersionUID = 1L;
Container container = getContentPane();
JLabel label = new JLabel("", JLabel.CENTER);
public MyDialog() {
super(MyFirstJPasswordField.this, "JDialog對話框", true);
this.setBounds(100, 100, 200, 200);
String password_string = new String(MyFirstJPasswordField.this.password_field.getPassword());
if (password_string.isEmpty()) label.setText("你的密碼不能為空");
else label.setText("你的密碼:" + password_string);
container.add(label);
this.setVisible(true);
}
}
class ButtonEvent implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
new MyDialog();
}
}
public MyFirstJPasswordField()
{
this.setBounds(50, 50, 400, 200);
password_field.setEchoChar('#');
button.addActionListener(new ButtonEvent());
panel_north.add(label);
panel_center.add(password_field);
panel_south.add(button);
container.setLayout(new BorderLayout());
container.add(panel_north, BorderLayout.NORTH);
container.add(panel_center, BorderLayout.CENTER);
container.add(panel_south, BorderLayout.SOUTH);
this.setVisible(true);
}
public static void main(String[] args)
{
new MyFirstJPasswordField();
}
}
效果圖如下:

