AWT绘图(验证码)

import java.awt.*;
import java.util.Random;
import javax.swing.*;
import java.awt.event.*;
public class SU {
	public static void main(String[] args) {
		final Frame frame = new Frame("验证码"); // 创建Frame对象
		final Panel panel = new MyPanel();       // 创建Canvas对象
		frame.add(panel);
		frame.setSize(200, 100);
		// 将Frame窗口居中
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
		MyWindowListener mw=new MyWindowListener();      
        frame.addWindowListener(mw); 
	}
}
class MyPanel extends Panel {
	public void paint(Graphics g) {
		int width = 180; // 定义验证码图片的宽度
		int height = 60; // 定义验证码图片的高度
		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, 30)); // 设置验证码字体
		g.setColor(Color.BLUE); // 设置验证码颜色
		// 产生随机验证码
		char[] chars = ("0123456789abcdefghijkmnopqrstuvwxyzABCDEFG"
				+ "HIJKLMNPQRSTUVWXYZ").toCharArray();
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < 4; i++) {
			int pos = r.nextInt(chars.length);
			char c = chars[pos];
			sb.append(c + " ");
		}
		g.drawString(sb.toString(), 20, 30); // 写入验证码
	}
} 
//关窗口
class MyWindowListener implements WindowListener {      
    // 监听器监听事件对象作出处理      
    public void windowClosing(WindowEvent e) {      
        Window window = e.getWindow();      
        window.setVisible(false);      
        // 释放窗口      
        window.dispose();      
    }   
    public void windowActivated(WindowEvent e) {      
    }      
    public void windowClosed(WindowEvent e) {      
    }      
    public void windowDeactivated(WindowEvent e) {      
    }      
    public void windowDeiconified(WindowEvent e) {      
    }      
    public void windowIconified(WindowEvent e) {      
    }      
    public void windowOpened(WindowEvent e) {      
    }      
     
}      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值