JAVA--生成验证码

来源:互联网 发布:社交软件文案 编辑:程序博客网 时间:2024/04/26 23:58
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CodeMatch extends JFrame{
   
    
    public CodeMatch(){
        
    }
    
    public static void main(String[] args){
        int width = 100;
        int height = 40;
        BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.setColor(new Color(100,100,100));
        g.fillRect(0,0,width,height);
        Random md = new Random();
        int randnum = md.nextInt(9000)+1000;
        String randstr = String.valueOf(randnum);
        g.setColor(Color.BLACK);
        g.setFont(new Font("",Font.PLAIN,20));
        g.drawString(randstr,30, 30);
        for(int i=0;i<100;i++){
            int x = md.nextInt(width);
            int y = md.nextInt(height);
            g.drawOval(x,y,1,1);
            
        }
        
        Image image = (Image)img;
       Panel pane = new Panel(image);
        
        JFrame frame = new JFrame();
        frame.add(pane);
        frame.setSize(100,70);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class Panel extends JPanel{
    Image img;
    public Panel(Image img){
        this.img = img;
        repaint();
    }
    
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);
        g.drawImage(img, 0, 0, getWidth(), getHeight(), this);

    }
}

0 0