下面的示例展示了如何在Java Swing应用程序中更改密码字段的回显字符。
使用以下API -
JPasswordField
- 创建密码字段。JPasswordField.getPassword()
- 获取密码。JPasswordField.setEchoChar(<)
- 设置密码字段的回显字符。
示例
package com.yiibai.swingdemo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTester {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingTester() {
prepareGUI();
}
public static void main(String[] args) {
SwingTester swingControlDemo = new SwingTester();
swingControlDemo.showPasswordFieldDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("Swing更改密码字符(yiibai.com)");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("", JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showPasswordFieldDemo() {
headerLabel.setText("Control in action: JPasswordField");
JLabel namelabel = new JLabel("用户名: ", JLabel.RIGHT);
JLabel passwordLabel = new JLabel("密码: ", JLabel.CENTER);
final JTextField userText = new JTextField(6);
final JPasswordField passwordText = new JPasswordField(6);
passwordText.setEchoChar('#');
JButton loginButton = new JButton("登录");
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "用户名 " + userText.getText();
data += ", 密码: " + new String(passwordText.getPassword());
statusLabel.setText(data);
}
});
controlPanel.add(namelabel);
controlPanel.add(userText);
controlPanel.add(passwordLabel);
controlPanel.add(passwordText);
controlPanel.add(loginButton);
mainFrame.setVisible(true);
}
}
执行上面示例代码,得到以下结果: