JPasswordField的用法

//一个只能输入数字的密码框

import javax.swing.*;
import java.awt.event.ActionListener;
import java.util.EventListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

class Demo extends JFrame implements ActionListener, KeyListener
{
    private JPasswordField password = new JPasswordField(30);
    private JButton but = new JButton("获取密码");
    public Demo()
    {
        password.setEchoChar('$');
        this.getContentPane().add(password);
        password.addKeyListener(this);
        this.getContentPane().add(but,"South");
        but.addActionListener(this);
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    public static void main(String[]args)
    {
        new Demo();
    }

    public void actionPerformed(ActionEvent e) {
        String password = String.valueOf(this.password.getPassword());
        if(password.length()==0)
        {
            JOptionPane.showMessageDialog(null,"密码不能为空");
            return;
        }
        JOptionPane.showMessageDialog(this,"您输入的密码为"+password);
    }

    public void keyTyped(KeyEvent e) {
        if(!Character.isDigit(e.getKeyChar())||e.getKeyCode()==KeyEvent.VK_SPACE)
        {
            e.setKeyChar((char)KeyEvent.VK_CLEAR);
        }
    }

    public void keyPressed(KeyEvent e) {
        
    }

    public void keyReleased(KeyEvent e) {
        
    }
}

你可能感兴趣的:(String,null)