📜  Java Swing-JPasswordField

📅  最后修改于: 2020-09-30 05:56:13             🧑  作者: Mango

Java JPasswordField

JPasswordField类的对象是专用于输入密码的文本组件。它允许编辑一行文本。它继承了JTextField类。

JPasswordField类声明

我们来看一下javax.swing.JPasswordField类的声明。

public class JPasswordField extends JTextField

常用的构造函数:

Constructor Description
JPasswordField() Constructs a new JPasswordField, with a default document, null starting text string, and 0 column width.
JPasswordField(int columns) Constructs a new empty JPasswordField with the specified number of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text.
JPasswordField(String text, int columns) Construct a new JPasswordField initialized with the specified text and columns.

Java JPasswordField示例

import javax.swing.*;  
public class PasswordFieldExample {
public static void main(String[] args) {  
JFrame f=new JFrame("Password Field Example");  
 JPasswordField value = new JPasswordField(); 
 JLabel l1=new JLabel("Password:");  
    l1.setBounds(20,100, 80,30);  
     value.setBounds(100,100,100,30);  
            f.add(value);  f.add(l1);
            f.setSize(300,300);  
            f.setLayout(null);  
            f.setVisible(true);   
}
}

输出:

带有ActionListener的Java JPasswordField示例

import javax.swing.*;  
import java.awt.event.*;
public class PasswordFieldExample {
public static void main(String[] args) {  
JFrame f=new JFrame("Password Field Example");  
 final JLabel label = new JLabel();          
 label.setBounds(20,150, 200,50);
 final JPasswordField value = new JPasswordField(); 
 value.setBounds(100,75,100,30); 
 JLabel l1=new JLabel("Username:");  
    l1.setBounds(20,20, 80,30);  
    JLabel l2=new JLabel("Password:");  
    l2.setBounds(20,75, 80,30);  
    JButton b = new JButton("Login");
    b.setBounds(100,120, 80,30);  
    final JTextField text = new JTextField();
    text.setBounds(100,20, 100,30);  
                f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);
                f.setSize(300,300);  
                f.setLayout(null);  
                f.setVisible(true);   
                b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {     
                   String data = "Username " + text.getText();
                   data += ", Password: " 
                   + new String(value.getPassword()); 
                   label.setText(data);        
                }
             }); 
}
}

输出: