swing组件之JPasswordField

1.JPasswordField 简介

Java官方api地址 https://docs.oracle.com/javase/8/docs/api/javax/swing/JPasswordField.html

JPasswordField是swing组件的一种,即密码框。JPasswordField 继承自 JTextField,只是显示输入的内容时用特定的字符替换显示(例如 * 或 ●),用法和 JTextField 基本一致。

2.JPasswordField 常用方法:

// 获取密码框输入的密码
char[] getPassword()

// 设置密码框的 密码文本、字体 和 字体颜色
void setText(String text)
void setFont(Font font)
void setForeground(Color fg)

// 设置密码框输入内容的水平对齐方式
void setHorizontalAlignment(int alignment)

// 设置密码框默认显示的密码字符
void setEchoChar(char c)

3.JPasswordField 常用监听器:

// 添加焦点事件监听器
void addFocusListener(FocusListener listener)

// 添加文本框内的 文本改变 监听器
textField.getDocument().addDocumentListener(DocumentListener listener)

// 添加按键监听器
void addKeyListener(KeyListener listener)

4. 事例

创建LoginTest类

import javax.swing.*;

public class LoginTest {
    public static void main(String[] args)
    {
        JFrame frame = new LoginComponentFrame();
        frame.setTitle("请输入用户名和密码进行登陆");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

创建LoginComponentFrame类

import javax.swing.*;
import java.awt.*;

public class LoginComponentFrame extends JFrame
{
    public static final int TEXTAREA_ROWS = 20;
    public static final int TEXTAREA_COLUMNS = 60;

    public LoginComponentFrame()
    {
        JTextField textField = new JTextField(15);
        JPasswordField passwordField = new JPasswordField(15);
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new GridLayout(2, 2));
        northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
        northPanel.add(textField);
        northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
        northPanel.add(passwordField);
        add(northPanel, BorderLayout.NORTH);
        JTextArea textArea = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLUMNS);
        textArea.setEnabled(false);
        textArea.setVisible(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane, BorderLayout.CENTER);

        // add button to append text into the text area
        JPanel southPanel = new JPanel();

        JButton insertButton = new JButton("登陆");
        insertButton.addActionListener(e -> {
            if(textField.getText().equals("user") &&
                    new String(passwordField.getPassword()).equals("1234")){
                LoginComponentFrame.this.setTitle("用户名密码输入正确,登陆成功。");
                textArea.setEnabled(true);
                textArea.setVisible(true);

            }
        });
        southPanel.add(insertButton);
        add(southPanel, BorderLayout.SOUTH);
        pack();
    }
}

运行结果如下:

发布了5 篇原创文章 · 获赞 3 · 访问量 494

猜你喜欢

转载自blog.csdn.net/qq_40552794/article/details/84350301