又进过了一周充实的学习
通过课上的练习和课下的编程以及查询资料
又是收获满满
今天分享一个验证码的程序
1 package 验证码; 2 3 import java.awt.Container; 4 import java.awt.FlowLayout; 5 import java.awt.event.ActionEvent; 6 import java.awt.event.ActionListener; 7 import java.util.Random; 8 9 import javax.swing.JButton; 10 import javax.swing.JFrame; 11 import javax.swing.JLabel; 12 import javax.swing.JOptionPane; 13 import javax.swing.JPanel; 14 import javax.swing.JPasswordField; 15 import javax.swing.JTextField; 16 17 @SuppressWarnings("unused") 18 public class Ma { 19 public static void main(String[] args) { 20 JFrame jf=new JFrame(); 21 JButton jb=new JButton("登录"); 22 JLabel idname=new JLabel("用户名"); //实例化JLabel对象 23 JLabel pastword=new JLabel("密 码"); 24 JLabel yzword=new JLabel("验证码"); 25 int[] random=new int[6]; 26 Random r=new Random(); 27 for(int i=0;i<6;i++) 28 { 29 random[i]=r.nextInt(10)+1; 30 } 31 String str=""; 32 for(int i=0;i<6;i++) 33 { 34 str=str+random[i]; 35 } 36 final String Str=str; 37 JLabel yzWord=new JLabel(str); 38 JTextField idtxt=new JTextField(15);//实例化用户名文本框 39 JPasswordField wordtxt=new JPasswordField(15);//实例化密码框 40 JTextField yzwordtxt=new JTextField(15); 41 wordtxt.setEchoChar('*');//将输入密码框中的密码以*显示出来 42 jf.setBounds(450,350,350,250); 43 jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 44 Container c=jf.getContentPane(); 45 c.setLayout(null); 46 c.add(jb); 47 c.add(idname); 48 c.add(idtxt); 49 c.add(pastword); 50 c.add(wordtxt); 51 c.add(yzword); 52 c.add(yzwordtxt); 53 c.add(yzWord); 54 idname.setBounds(10,40,50,18); 55 pastword.setBounds(10,80,50,18); 56 yzword.setBounds(10,120,50,18); 57 yzWord.setBounds(60,160,80,18); 58 idtxt.setBounds(60,40,200,18); 59 wordtxt.setBounds(60,80,200,18); 60 yzwordtxt.setBounds(60,120,200,18); 61 jb.setBounds(200,150,60,40); 62 jb.addActionListener(new ActionListener() { 63 public void actionPerformed(ActionEvent arg0) 64 { 65 if(idtxt.getText().trim().equals("20193941") 66 &&new String(wordtxt.getPassword()).equals("010011") 67 &&yzwordtxt.getText().trim().equals(Str)) 68 { 69 JOptionPane.showMessageDialog(null,"登录成功"); 70 } 71 if(yzwordtxt.getText().trim().equals(Str) 72 &&(!idtxt.getText().trim().equals("20193941") 73 ||!(new String(wordtxt.getPassword()).equals("010011")))) 74 { 75 JOptionPane.showMessageDialog(null,"用户名或密码错误"); 76 } 77 if(idtxt.getText().trim().equals("123456") 78 &&new String(wordtxt.getPassword()).equals("654321") 79 &&!yzwordtxt.getText().trim().equals(Str)) 80 { 81 JOptionPane.showMessageDialog(null,"验证码错误"); 82 } 83 } 84 }); 85 jf.setVisible(true); 86 } 87 }