课后作业:验证码
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 LoginWithCaptcha extends JFrame {
private JTextField usernameField;
private JPasswordField passwordField;
private JTextField captchaField;
private JLabel captchaLabel;
private String captchaString;
public LoginWithCaptcha() {
this.setTitle("登录界面");
this.setSize(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
createUI();
generateAndSetCaptchaImage();
}
private void createUI() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 2));
panel.setBackground(new Color(173, 216, 230));
addComponentsToPanel(panel);
this.add(panel);
}
private void addComponentsToPanel(JPanel panel) {
panel.add(new JLabel("账号:"));
usernameField = new JTextField();
panel.add(usernameField);
panel.add(new JLabel("密码:"));
passwordField = new JPasswordField();
panel.add(passwordField);
panel.add(new JLabel("验证码:"));
captchaField = new JTextField();
panel.add(captchaField);
captchaLabel = new JLabel();
panel.add(captchaLabel);
JButton refreshButton = createRefreshButton();
panel.add(refreshButton);
}
private JButton createRefreshButton() {
JButton refreshButton = new JButton("刷新");
refreshButton.setFont(new Font("Sans Serif", Font.BOLD, 14));
refreshButton.setBackground(Color.WHITE);
refreshButton.setForeground(Color.BLACK);
refreshButton.setFocusPainted(false);
refreshButton.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
generateAndSetCaptchaImage();
}
});
return refreshButton;
}
private void generateAndSetCaptchaImage() {
captchaString = generateRandomCaptcha();
BufferedImage captchaImage = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB
Graphics g = captchaImage.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 200, 100);
g.setColor(Color.BLACK);
g.setFont(new Font("Sans Serif", Font.PLAIN, 40));
g.drawString(captchaString, 20, 60);
g.dispose();
captchaLabel.setIcon(new ImageIcon(captchaImage));
}
private String generateRandomCaptcha() {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder captcha = new StringBuilder();
for (int i = 0; i < 4; i++) {
int index = random.nextInt(chars.length());
captcha.append(chars.charAt(index));
}
return captcha.toString();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new LoginWithCaptcha().setVisible(true));
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现