验证码界面
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;
public class VerificationCode extends JFrame {
private String code = "";
private JTextField codeText;
private JButton button1;
VerificationCode() {
super();
setResizable(false);
setTitle("Java实现验证码功能");
setBounds(700, 450, 300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
getContentPane().add(panel, BorderLayout.CENTER);
JLabel label1 = new JLabel();
label1.setText("验证码:");
label1.setBounds(10, 100, 50, 20);
panel.add(label1);
JTextField codeText = new JTextField();
codeText.setBounds(60, 100, 100, 20);
panel.add(codeText);
JButton button1 = new JButton("确定");
button1.setBounds(60, 140, 80, 20);
panel.add(button1);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String info = "";
if (codeText.getText() == null)
info = "验证码为空";
else if (!codeText.getText().equalsIgnoreCase(code))
info = "验证码错误";
else
System.exit(0);
JOptionPane.showMessageDialog(null, info);
}
});
}
public void paint(Graphics g){
BufferedImage image = new BufferedImage(200, 100, 1);
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.GREEN);
Stroke stroke = new BasicStroke(2.0f);
graphics.setStroke(stroke);
graphics.setFont(new Font("仿宋", Font.BOLD, 20));
Random r = new Random();
for (int i = 1; i <= 8; i++) {
char c;
String C="";
switch (r.nextInt(2) + 1) {
case 1:
c = (char)(r.nextInt(9) + 48);
C+=c;
graphics.drawString(C, i * 10, 30);
code += c;
break;
case 2:
c = (char) (r.nextInt(26) + 65);
graphics.drawString(C+c, i * 10, 30);
code += c;
break;
case 3:
c = (char) (r.nextInt(26) + 97);
graphics.drawString(C+c, i * 10, 30);
code += c;
break;
}
}
g.drawImage(image, 40, 20, null);
}
public static void main(String[] args) {
VerificationCode frame = new VerificationCode();
frame.setVisible(true);
}
标签:codeText,code,graphics,星期三,import,new,panel From: https://www.cnblogs.com/chukjbgg333/p/17700420.html