课后作业:验证码
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));
}
}