Java:JPasswordField类

JPasswordField密码框组件,其实跟JTextField文本框组件的使用非常相似,只不过多了一个回显字符而已。

JPasswordField类所在包

JPasswordField类的所在包不用说大家都知道是javax.swing包了,所以开头导入。

import javax.swing.*;

JPasswordField类构造方法

public JPasswordField();
public JPasswordField(String text);
public JPasswordField(int fieldwidth);
public JPasswordField(String text, int fieldwidth);

主要的构造方法就这些,这里简单说一下text就是密码框中的初始密码,fieldwidth就是密码框的宽度。

JPasswordField类使用方法

其实我认为JPasswordField类最主要的方法就是下面这个设置回显字符的方法了。其中的字符c就是回显字符。这里默认回显字符是一个点。

password_field.setEchoChar(c);

剩下的大部分方法就几乎和JTextField类完全一样了,就是在获取文本上有一点点区别,JPasswordField类获取的是密码,所以翻译成英文就是getPassword。但这里务必注意该方法返回的是一个char类型的数组,所以得用String类型的构造方法将其转换为字符串,代码如下。

new String(password_field.getPassword());

代码

package technology;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyFirstJPasswordField extends JFrame {
	final static long serialVersionUID = 1L;
	Container container = getContentPane();
	JLabel label = new JLabel("请输入你的密码:");
	JPanel panel_north = new JPanel(), panel_center = new JPanel(), panel_south = new JPanel();
	JButton button = new JButton("确认");
	JPasswordField password_field = new JPasswordField("000000", 20);
	
	class MyDialog extends JDialog {
		final static long serialVersionUID = 1L;
		Container container = getContentPane();
		JLabel label = new JLabel("", JLabel.CENTER);
		
		public MyDialog() {
			super(MyFirstJPasswordField.this, "JDialog对话框", true);
			this.setBounds(100, 100, 200, 200);
			String password_string = new String(MyFirstJPasswordField.this.password_field.getPassword());
			if (password_string.isEmpty()) label.setText("你的密码不能为空");
			else label.setText("你的密码:" + password_string);
			container.add(label);
			this.setVisible(true);
		}
	}
	
	class ButtonEvent implements ActionListener {
		public void actionPerformed(ActionEvent arg0) {
			new MyDialog();
		}
	}
	
	public MyFirstJPasswordField()
	{
		this.setBounds(50, 50, 400, 200);
		password_field.setEchoChar('#');
		button.addActionListener(new ButtonEvent());
		panel_north.add(label);
		panel_center.add(password_field);
		panel_south.add(button);
		container.setLayout(new BorderLayout());
		container.add(panel_north, BorderLayout.NORTH);
		container.add(panel_center, BorderLayout.CENTER);
		container.add(panel_south, BorderLayout.SOUTH);
		this.setVisible(true);
	}
	
	public static void main(String[] args)
	{
		new MyFirstJPasswordField();
	}
}

效果图如下:

在这里插入图片描述

posted @ 2020-03-20 11:09  000紫外线000  阅读(1118)  评论(0编辑  收藏  举报