Java登陸驗證碼問題
阿新 • • 發佈:2017-10-08
str button ace pla round 截圖 輸入 todo 技術分享
程序設計思路
隨機產生一個6位的字符串
讀取用戶輸入的信息,包括賬號密碼。
驗證用戶輸入的驗證碼是不是和產生的隨機字符串一樣。
如果不是一樣的話就提示並且回到重新輸入的界面。
如果一樣的話就提示登陸成功,並且刷新驗證碼,以方便下一個用戶的使用。
程序流程圖
程序源代碼
import java.awt.Color; import java.awt.Component; public static void main(String[] args) { // TODO 自動生成的方法存根 JFrame frame=new JFrame("登陸測試"); frame.setBounds(500, 300, 350, 200); frame.setSize(350,200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Panel panel=new Panel(); frame.add(panel); placeCompoents(panel); panel.setBackground(Color.LIGHT_GRAY); frame.setVisible(true); } private static void placeCompoents(Panel panel) { // TODO 自動生成的方法存根 panel.setLayout(null); //姓名信息 JLabel userLabel=new JLabel("User"); userLabel.setBounds(10, 20, 80, 25); panel.add(userLabel); JTextField userText=new JTextField(20); userText.setBounds(100, 20, 165, 25); panel.add(userText); //密碼信息 JLabel passwordLabel=new JLabel("password"); passwordLabel.setBounds(10, 50, 80, 25); panel.add(passwordLabel); JPasswordField passwordText=new JPasswordField(20); passwordText.setBounds(100, 50, 165, 25); panel.add(passwordText); //驗證碼信息 String code=""; for(int i=0;i<6;i++) { int intVal=(int)(Math.random()*26+97); code=code+(char)intVal; } String codex=code; JLabel ident=new JLabel(code); ident.setBounds(200, 80, 80, 25); panel.add(ident); // 驗證碼文本域 JLabel codes=new JLabel("codes"); codes.setBounds(10, 80, 80, 25); panel.add(codes); JTextField codeText=new JTextField(6); codeText.setBounds(100, 80, 80, 25); panel.add(codeText); //按鈕 JButton loginButton=new JButton("login"); loginButton.setBounds(100, 100, 80, 25); panel.add(loginButton); loginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String c=codeText.getText(); String u=userText.getText(); char[] p1=passwordText.getPassword(); String p=""; p=p.valueOf(p1); if(c.equals(codex)) { JOptionPane.showMessageDialog(null,"hello "+u+",歡迎使用!祝您一天愉快"); // userText.setText("你媽媽喊你回家吃飯"); passwordText.setText(""); codeText.setText(""); String code=""; for(int i=0;i<6;i++) { int intVal=(int)(Math.random()*26+97); code=code+(char)intVal; } String codex=code; ident.setText(codex); } else { JOptionPane.showMessageDialog(null,"驗證碼錯誤"); } } } ); JButton exit=new JButton("exit"); exit.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } } ); exit.setBounds(200, 100, 80, 25); panel.add(exit); } }
程序運行截圖
Java登陸驗證碼問題