How to write simple captcha software with Java
982 viewsThis is a demo I wrote earlier today to show you how you can write captcha software with Java. The application is really basic and currently only supports numbers but the code can be modified easily to support text. I’ll probably add this features later when i have the time to code it. Until then, here’s the JCaptcha code that works with numbers:
code:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Captcha extends JFrame implements ActionListener{
static String userDir = System.getProperty(”user.dir”);
JLabel imageOne, imageTwo,imageThree,imageFour, validateNumber, message;
JTextField input = new JTextField();
JButton check, newCaptcha;
int random;
String captcha = “”;
public static void main(String[] args) {
Captcha c = new Captcha();
c.showGui();
}
public void showGui(){
getContentPane().setLayout(null);
setRandomNumber();
captcha = captcha+random;
imageOne = new JLabel(new ImageIcon(userDir + “\\images\\” + random + “.gif”));
imageOne.setBounds(0,0,50,50);
add(imageOne);
setRandomNumber();
captcha = captcha+random;
imageTwo = new JLabel(new ImageIcon(userDir + “\\images\\” + random + “.gif”));
imageTwo.setBounds(0,0,95,50);
add(imageTwo);
setRandomNumber();
captcha = captcha+random;
imageThree = new JLabel(new ImageIcon(userDir + “\\images\\” + random + “.gif”));
imageThree.setBounds(0,0,140,50);
add(imageThree);
setRandomNumber();
captcha = captcha+random;
imageFour = new JLabel(new ImageIcon(userDir + “\\images\\” + random + “.gif”));
imageFour.setBounds(0,0,185,50);
add(imageFour);
validateNumber = new JLabel(”Enter the numbers shown above.”);
validateNumber.setBounds(15,0,250,100);
add(validateNumber);
input = new JTextField(10);
input.setBounds(15,60,60,20);
add(input);
check = new JButton(”Validate”);
check.addActionListener(this);
check.setBounds(80,60,180,20);
add(check);
message = new JLabel(”");
message.setBounds(15,40, 100,100);
add(message);
newCaptcha = new JButton(”Generate new Captcha”);
newCaptcha.addActionListener(this);
newCaptcha.setBounds(80,80,180,20);
add(newCaptcha);
setTitle(”Java Captcha - Engineeringserver.com”);
setSize(300,150);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
//System.out.println(captcha);
}
public void setRandomNumber(){
random = (int) (0+(Math.random())*9);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == check){
if(input.getText().equals(captcha)){
message.setForeground(Color.GREEN);
message.setText(”Correct!”);
//code here to continue..
}
else{
message.setForeground(Color.RED);
message.setText(”try again!”);
}
}
if(e.getSource() == newCaptcha){
this.dispose();
Captcha c = new Captcha();
c.showGui();
}
}
}













