PasswordDemo

本文介绍了一个简单的 Java Swing 应用程序示例,该程序展示如何使用 JPasswordField 控件来创建一个带有密码输入功能的界面,并通过 JButton 触发事件来显示用户输入的用户名和密码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

博客上的文章太少了,所以把这个也贴到这了。大家扔砖头吧。
java 代码
 
  1. import javax.swing.*;  
  2. import java.awt.*;  
  3. import java.awt.event.*;  
  4.   
  5. public class PasswordDemo{  
  6.     // 口令和文本输入域  
  7.     JPasswordField passwordField = new JPasswordField(12);  
  8.     JTextField textField = new JTextField(12);  
  9.   
  10.     public static void main(String[] args){  
  11.         PasswordDemo pd = new PasswordDemo();  
  12.         pd.go();  
  13.     }  
  14.   
  15.     void go(){  
  16.         // 设置口令回显字符为X  
  17.         passwordField.setEchoChar('X');  
  18.         // 创建各个标签、按钮  
  19.         final JFrame f = new JFrame("PasswordDemo");  
  20.         JLabel label1 = new JLabel("输入用户名: ");  
  21.         JLabel label2 = new JLabel("输入口令");  
  22.         JButton button1 = new JButton("确定");  
  23.         JButton button2 = new JButton("取消");  
  24.   
  25.         // 鼠标单击“OK”按钮则执行这段代码  
  26.         button1.addActionListener(new ActionListener(){  
  27.             public void actionPerformed(ActionEvent e){  
  28.                 // 获取输入的名字  
  29.                 String name = textField.getText();  
  30.                 // 获取输入的口令值  
  31.                 char[] password = passwordField.getPassword();  
  32.                 System.out.println("输入用户名: " + name);  
  33.                 System.out.println("输入口令: "new String(password));  
  34.             }  
  35.         });  
  36.   
  37.         // 使用网络布局  
  38.         JPanel contentPane = new JPanel(new GridLayout(3,2));  
  39.         contentPane.add(label1);  
  40.         contentPane.add(textField);  
  41.         contentPane.add(label2);  
  42.         contentPane.add(passwordField);  
  43.         contentPane.add(button1);  
  44.         contentPane.add(button2);  
  45.         f.setContentPane(contentPane);  
  46.   
  47.         // 关闭窗口  
  48.         f.addWindowListener(new WindowAdapter(){  
  49.             public void windowClosing(WindowEvent e){  
  50.                 System.exit(0);  
  51.             }  
  52.         });  
  53.         f.pack();  
  54.         f.setVisible(true);  
  55.     }  
  56. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值