java swing 实现随机背景验证码的效果

此文是为kuzalid解决以下问题的:

Java小程序的问题,用Canvas类实现验证码的效果,请大伙们指教 

http://topic.csdn.net/u/20090623/07/5ae58582-33ae-46ed-aae3-86c3edf8057a.html?66995

 

 

 /** * 使用图形输出验证码效果(随机数字) * Cavas Random Graphics **/ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; public class Exseven extends JFrame implements ActionListener { JButton button; ImgCanvas canvas; public Exseven() { super("验证码-CSDN.huadis"); setBackground(Color.white); setLayout(new BorderLayout()); setSize(300, 150); setLocation(200, 200); button = new JButton("验证码"); button.addActionListener(this); canvas = new ImgCanvas(); canvas.setSize(180, 70); canvas.setOpaque(true); canvas.setVisible(true); add(canvas,BorderLayout.CENTER); add(button,BorderLayout.SOUTH); setVisible(true); } public static void main(String[] args) { new Exseven(); } public void actionPerformed(ActionEvent e) { if(e.getSource()==button){ canvas.repaint(); } } private class ImgCanvas extends JComponent{ public ImgCanvas(){ super(); } public void paintComponent(Graphics g){ Random ra=new Random(); char st[]="1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); g.setColor(new Color(ra.nextInt(256),ra.nextInt(256),ra.nextInt(256))); g.fillRect(0, 0, getWidth(), getHeight()); Font f=new Font("Fixedsys",Font.PLAIN,50); g.setColor(new Color(ra.nextInt(100),ra.nextInt(100),ra.nextInt(100)));//设置验证码随机色彩 g.setFont(f); //随机生成四个数字与字母的组合,+""必须有,意思是把四个字符连结起来变成字符串String String ss=new String(st[ra.nextInt(36)]+""+st[ra.nextInt(36)]+st[ra.nextInt(36)]+st[ra.nextInt(36)]); g.drawString(ss, 20, 50); g.drawLine(10, 10, 170, 60); g.drawLine(10, 40, 170, 20); } } }

你可能感兴趣的:(我的话题)