随机验证码实验报告
2018-10-08 08:49 一念永恒s 阅读(523) 评论(0) 编辑 收藏 举报程序设计思想
定义一个Gui类,在类内创建控制对象,用户文本,密码文本,用户输入框,密码输入框,确认按钮,退出按钮,验证码文本,验证码文本框,验证码,定义一个 Mypanel类,设置验证码框背景颜色,设置验证码颜色,设置验证码,随机产生验证码,在主函数中新建对象。
源程序
package Homework;
import java.awt.*;
import javax.swing.*;
public class Gui extends JFrame {
private JLabel userLa;
private JLabel pwdLa;
private JLabel verCodeLa;//验证码
private JTextField userTxt;
private JPasswordField pwdTxt;
private JTextField verCodeTxt;//验证码
private JButton sureBt;
private JButton quitBt;
private Mypanel mp;
//构造方法
public Gui()
{
Init();
}
public void Init()
{
this.setTitle("请登入");
//创建出控件对象(因为上面只是声明出来,并没有给出实际的空间)
//用户文本
userLa = new JLabel();
userLa.setText("用户名:");
userLa.setSize(60, 50);
userLa.setLocation(100, 80);
//密码文本
pwdLa = new JLabel();
pwdLa.setText("密码:");
pwdLa.setSize(50, 50);
pwdLa.setLocation(100, 120);
//用户输入框
userTxt = new JTextField();
userTxt.setSize(100, 20);
//this.setSize(width, height)
userTxt.setLocation(170, 95);
//密码输入框
pwdTxt = new JPasswordField();
pwdTxt.setSize(100, 20);
pwdTxt.setLocation(170, 135);
//确认按钮
sureBt = new JButton("登录");
sureBt.setSize(60, 25);
sureBt.setLocation(135, 260);
//退出按钮
quitBt = new JButton("快速注册");
quitBt.setSize(100, 25);
quitBt.setLocation(240, 260);
//验证码文本
verCodeLa = new JLabel();
verCodeLa.setText("验证码:");
verCodeLa.setSize(60, 50);
verCodeLa.setLocation(100,165);
//验证码文本框
verCodeTxt = new JTextField();
verCodeTxt.setSize(100, 20);
verCodeTxt.setLocation(170, 180);
//验证码
mp = new Mypanel();
mp.setSize(100, 30);
mp.setLocation(280, 175);
this.setLayout(null);
this.setSize(500, 400);
this.add(userLa);
this.add(pwdLa);
this.add(userTxt);
this.add(pwdTxt);
this.add(sureBt);
this.add(quitBt);
this.add(verCodeLa);
this.add(verCodeTxt);
this.add(mp);
this.setVisible(true);
}
public static void main(String[] args) {
new Gui();
}
}
package Homework;
import java.awt.*;
import java.util.*;
public class Mypanel extends Panel {
public void paint(Graphics g)
{
int height = 50;
int width = 90;
//验证码框背景颜色
g.setColor(Color.LIGHT_GRAY);
//填充验证码背景
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);
Random r = new Random();
//设置干扰点
for(int i = 0;i<100;i++)
{
int x = r.nextInt(width)-1;
int y = r.nextInt(height)-1;
g.drawOval(x, y, 2, 2);
}
g.setFont(new Font("黑体",Font.BOLD,20));//设置验证码字体以及大小
g.setColor(Color.red);//设置验证码字体颜色
//生成随机验证码
char[] tmp = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
StringBuilder sb = new StringBuilder();
for(int i = 0;i<4;i++)
{
int pos = r.nextInt(tmp.length);
char c = tmp[pos];
sb.append(c + " ");
}
g.drawString(sb.toString(), 10, 15);//写入验证码
}
}
实验结果截图
实验总结
在编程时,在编写输出语句时,内部的关系容易混乱,尤其是加法运算时,在编写时更容易混乱。