java第一次上机实验--验证码
1 package javashiyan; 2 3 import java.awt.Color; 4 import java.awt.event.ActionEvent; 5 import java.awt.event.ActionListener; 6 7 import javax.swing.*; 8 9 public class Yanzhen extends JFrame 10 { 11 //定义成员变量 12 private Mypanel mp; 13 private JButton b; 14 private JTextField txt; 15 private ActionListener listener; 16 17 public Yanzhen() 18 { 19 Realize(); 20 } 21 public void Realize() 22 { 23 JFrame f=new JFrame("验证码"); 24 //实例化 25 b=new JButton(); 26 b.addActionListener(listener); 27 ActionEvent e; 28 b.setIcon(new ImageIcon("D://button//刷新.jpg"));//载入图片 29 b.setLocation(200,100);//设置位置 30 b.setSize(32,32);//设置大小 31 b.setVisible(true);//设置显示 32 33 txt=new JTextField(); 34 txt.setSize(90,30); 35 txt.setLocation(10,100); 36 txt.setVisible(true); 37 38 mp=new Mypanel(); 39 mp.setSize(100,30); 40 mp.setLocation(100,100); 41 42 JButton jb=new JButton(); 43 44 45 f.add(mp); 46 f.add(b); 47 f.add(txt); 48 49 f.setLayout(null); 50 f.setSize(400, 400);//设置界面大小 51 f.getContentPane().setBackground(Color.white);//设置界面的背景颜色 52 f.getContentPane().setVisible(true); 53 f.setVisible(true); 54 } 55 56 57 58 public void actionPerformed(ActionEvent e) { 59 // TODO Auto-generated method stub 60 61 62 } 63 }
1 package javashiyan; 2 3 import java.awt.*; 4 import java.util.*; 5 6 public class Mypanel extends Panel { 7 public void paint(Graphics g) 8 { 9 int height = 50; 10 int width = 90; 11 //验证码框背景颜色 12 g.setColor(Color.white); 13 //填充验证码背景 14 g.fillRect(0, 0, width, height); 15 g.setColor(Color.BLACK); 16 g.drawRect(0, 0, width-1, height-1); 17 Random r = new Random(); 18 for(int i = 0;i<100;i++) 19 { 20 int x = r.nextInt(width)-1; 21 int y = r.nextInt(height)-1; 22 g.drawOval(x, y, 2, 2);//画干扰的圆点 23 } 24 for(int i=0;i<3;i++) 25 { 26 int x1=r.nextInt(width)-1; 27 int y1=r.nextInt(height)-1; 28 int x2=r.nextInt(width)-1; 29 int y2=r.nextInt(height)-1; 30 g.drawLine(x1, y1, x2, y2);//画干扰的线段 31 } 32 33 g.setFont(new Font("黑体",Font.BOLD,20));//设置验证码字体以及大小 34 g.setColor(Color.BLUE);//设置验证码字体颜色 35 //生成随机验证码 36 char[] tmp = ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); 37 StringBuilder sb = new StringBuilder(); 38 for(int i = 0;i<4;i++) 39 { 40 int pos = r.nextInt(tmp.length); 41 char c = tmp[pos]; 42 sb.append(c + " "); 43 } 44 g.drawString(sb.toString(), 10, 15);//写入验证码 45 } 46 }
1 package javashiyan; 2 3 4 5 import java.util.Random; 6 7 public class main { 8 9 public static void main(String[] args) 10 { 11 Yanzhen dang=new Yanzhen(); 12 } 13 14 } 15