pull/1/head
wrh 7 months ago
parent 310e4265e5
commit c8540e33f4

@ -1,11 +1,11 @@
import controller.NavigationController;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
public class MathLearningApp {
public static void main(String[] args) {
// Set system look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
@ -13,7 +13,9 @@ public class MathLearningApp {
// Start the application
SwingUtilities.invokeLater(() -> {
NavigationController.showLoginView();
// 获取 NavigationController 实例并显示登录界面
NavigationController navigationController = NavigationController.getInstance();
navigationController.showLoginView();
});
}
}

@ -0,0 +1,41 @@
package controller;
import javax.swing.JOptionPane;
public abstract class BaseController {
protected void validateNotNull(Object obj, String fieldName) {
if (obj == null) {
throw new IllegalArgumentException(fieldName + "不能为空");
}
}
protected void validateStringNotEmpty(String str, String fieldName) {
if (str == null || str.trim().isEmpty()) {
throw new IllegalArgumentException(fieldName + "不能为空");
}
}
protected void validateStringLength(String str, String fieldName, int min, int max) {
validateStringNotEmpty(str, fieldName);
if (str.length() < min || str.length() > max) {
throw new IllegalArgumentException(fieldName + "长度应在" + min + "-" + max + "之间");
}
}
protected void showError(String message) {
JOptionPane.showMessageDialog(null, message, "错误", JOptionPane.ERROR_MESSAGE);
}
protected void showSuccess(String message) {
JOptionPane.showMessageDialog(null, message, "成功", JOptionPane.INFORMATION_MESSAGE);
}
protected void logInfo(String message) {
//System.out.println(" " + message);
}
protected void logError(String message) {
System.err.println("❌ " + message);
}
}

@ -7,71 +7,116 @@ import view.MainView;
import view.ExamView;
import view.ResultView;
public class NavigationController extends BaseController implements NavigationService {
private static NavigationController instance;
private LoginView loginView;
private RegisterView registerView;
private MainView mainView;
private ExamView examView;
private ResultView resultView;
private User currentUser;
public class NavigationController {
private static LoginView loginView;
private static RegisterView registerView;
private static MainView mainView;
private static ExamView examView;
private static ResultView resultView;
private static User currentUser; // 保存当前登录用户
// 单例模式
public static NavigationController getInstance() {
if (instance == null) {
instance = new NavigationController();
}
return instance;
}
private NavigationController() {
// 私有构造函数
}
public static void showLoginView() {
@Override
public void showLoginView() {
if (loginView == null) {
loginView = new LoginView();
}
loginView.setVisible(true);
hideAllExcept(loginView);
logInfo("显示登录界面");
}
public static void showRegisterView() {
@Override
public void showRegisterView() {
if (registerView == null) {
registerView = new RegisterView();
}
registerView.setVisible(true);
hideAllExcept(registerView);
logInfo("显示注册界面");
}
// 修改:传递用户信息到主界面
public static void showMainView(User user) {
currentUser = user;
@Override
public void showMainView(User user) {
setCurrentUser(user);
if (mainView != null) {
mainView.dispose(); // 关闭旧的主界面
mainView.dispose();
}
mainView = new MainView(user); // 创建新的主界面
mainView = new MainView(user);
mainView.setVisible(true);
hideAllExcept(mainView);
logInfo("显示主界面 - 用户: " + user.getUsername());
}
// 新增:无参数版本,使用当前保存的用户
public static void showMainView() {
@Override
public void showMainView() {
if (currentUser != null) {
showMainView(currentUser);
} else {
// 如果没有保存的用户,返回登录界面
showLoginView();
}
}
public static void showExamView(String difficulty, int questionCount) {
if (examView == null) {
examView = new ExamView();
@Override
public void showExamView(String difficulty, int questionCount) {
try {
validateStringNotEmpty(difficulty, "难度");
if (questionCount <= 0) {
throw new IllegalArgumentException("题目数量必须大于0");
}
if (examView == null) {
examView = new ExamView();
}
examView.startNewExam(difficulty, questionCount);
examView.setVisible(true);
hideAllExcept(examView);
logInfo("显示考试界面 - " + difficulty + "难度, " + questionCount + "道题");
} catch (Exception e) {
logError("显示考试界面异常: " + e.getMessage());
showError("无法开始考试: " + e.getMessage());
}
examView.startNewExam(difficulty, questionCount);
examView.setVisible(true);
hideAllExcept(examView);
}
public static void showResultView(int score, int total, double percentage) {
if (resultView == null) {
resultView = new ResultView();
@Override
public void showResultView(int score, int total, double percentage) {
try {
if (resultView == null) {
resultView = new ResultView();
}
resultView.setResults(score, total, percentage);
resultView.setVisible(true);
hideAllExcept(resultView);
logInfo("显示成绩界面 - 得分: " + score + "/" + total);
} catch (Exception e) {
logError("显示成绩界面异常: " + e.getMessage());
}
resultView.setResults(score, total, percentage);
resultView.setVisible(true);
hideAllExcept(resultView);
}
private static void hideAllExcept(javax.swing.JFrame visibleFrame) {
@Override
public void setCurrentUser(User user) {
this.currentUser = user;
logInfo("设置当前用户: " + (user != null ? user.getUsername() : "null"));
}
@Override
public User getCurrentUser() {
return currentUser;
}
private void hideAllExcept(javax.swing.JFrame visibleFrame) {
javax.swing.JFrame[] frames = {loginView, registerView, mainView, examView, resultView};
for (javax.swing.JFrame frame : frames) {
if (frame != null && frame != visibleFrame) {
@ -79,5 +124,4 @@ public class NavigationController {
}
}
}
}

@ -0,0 +1,14 @@
package controller;
import model.User;
public interface NavigationService {
void showLoginView();
void showRegisterView();
void showMainView(User user);
void showMainView();
void showExamView(String difficulty, int questionCount);
void showResultView(int score, int total, double percentage);
void setCurrentUser(User user);
User getCurrentUser();
}

@ -6,7 +6,7 @@ import utils.FileUtil;
import java.util.List;
import java.util.Arrays;
public class QuestionController {
public class QuestionController extends BaseController implements QuestionService {
private QuestionGenerator generator = new QuestionGenerator();
private List<Question> currentQuestions;
private int currentQuestionIndex = 0;
@ -15,23 +15,39 @@ public class QuestionController {
private String currentDifficulty;
private int currentQuestionCount;
@Override
public void startNewExam(String difficulty, int questionCount) {
currentQuestions = generator.generateQuestions(questionCount, difficulty);
currentQuestionIndex = 0;
score = 0;
userAnswers = new int[questionCount];
Arrays.fill(userAnswers, -1);
currentDifficulty = difficulty;
currentQuestionCount = questionCount;
try {
validateStringNotEmpty(difficulty, "难度");
if (questionCount <= 0 || questionCount > 100) {
throw new IllegalArgumentException("题目数量必须在1-100之间");
}
// 保存试卷到本地
FileUtil.saveCurrentExam(currentQuestions, difficulty, questionCount);
currentQuestions = generator.generateQuestions(questionCount, difficulty);
currentQuestionIndex = 0;
score = 0;
userAnswers = new int[questionCount];
Arrays.fill(userAnswers, -1);
currentDifficulty = difficulty;
currentQuestionCount = questionCount;
System.out.println("🎯 生成新试卷: " + difficulty + " 难度, " + questionCount + " 道题");
FileUtil.saveCurrentExam(currentQuestions, difficulty, questionCount);
logInfo("生成新试卷: " + difficulty + " 难度, " + questionCount + " 道题");
} catch (Exception e) {
logError("开始新考试异常: " + e.getMessage());
throw e;
}
}
@Override
public String getCurrentExamInfo() {
if (currentDifficulty != null && currentQuestionCount > 0) {
return currentDifficulty + "难度 - " + currentQuestionCount + "道题";
}
return "暂无试卷";
}
// 其他方法保持不变...
@Override
public Question getCurrentQuestion() {
if (currentQuestions == null || currentQuestionIndex >= currentQuestions.size()) {
return null;
@ -39,25 +55,33 @@ public class QuestionController {
return currentQuestions.get(currentQuestionIndex);
}
@Override
public void submitAnswer(int answer) {
if (currentQuestionIndex < userAnswers.length) {
userAnswers[currentQuestionIndex] = answer;
logInfo("提交答案: 第" + getCurrentQuestionNumber() + "题, 答案: " + answer);
}
}
@Override
public boolean nextQuestion() {
currentQuestionIndex++;
return currentQuestionIndex < currentQuestions.size();
boolean hasNext = currentQuestionIndex < currentQuestions.size();
logInfo("下一题: " + (hasNext ? "有" : "无"));
return hasNext;
}
@Override
public boolean previousQuestion() {
if (currentQuestionIndex > 0) {
currentQuestionIndex--;
logInfo("上一题: 第" + getCurrentQuestionNumber() + "题");
return true;
}
return false;
}
@Override
public int calculateScore() {
score = 0;
for (int i = 0; i < currentQuestions.size(); i++) {
@ -65,21 +89,28 @@ public class QuestionController {
score++;
}
}
logInfo("计算得分: " + score + "/" + currentQuestions.size());
return score;
}
@Override
public double getPercentage() {
return (double) score / currentQuestions.size() * 100;
double percentage = (double) score / currentQuestions.size() * 100;
logInfo("正确率: " + String.format("%.1f%%", percentage));
return percentage;
}
@Override
public int getCurrentQuestionNumber() {
return currentQuestionIndex + 1;
}
@Override
public int getTotalQuestions() {
return currentQuestions != null ? currentQuestions.size() : 0;
}
@Override
public int getUserAnswerForCurrentQuestion() {
return userAnswers[currentQuestionIndex];
}

@ -0,0 +1,17 @@
package controller;
import model.Question;
public interface QuestionService {
void startNewExam(String difficulty, int questionCount);
Question getCurrentQuestion();
void submitAnswer(int answer);
boolean nextQuestion();
boolean previousQuestion();
int calculateScore();
double getPercentage();
int getCurrentQuestionNumber();
int getTotalQuestions();
int getUserAnswerForCurrentQuestion();
String getCurrentExamInfo();
}

@ -5,130 +5,152 @@ import utils.FileUtil;
import utils.ValidationUtil;
import utils.EmailUtil;
public class UserController {
public class UserController extends BaseController implements UserService {
public void cleanuers(){
FileUtil.cleanupUnregisteredUsers();
}
/**
* -
*/
@Override
public String registerUser(String username, String email) {
// 验证用户名
if (username == null || username.trim().isEmpty()) {
return "用户名不能为空";
}
if (username.length() < 2 || username.length() > 20) {
return "用户名长度应为2-20个字符";
}
// 验证邮箱
if (!ValidationUtil.isValidEmail(email)) {
return "邮箱格式不正确";
}
// 检查用户名是否已存在
if (FileUtil.usernameExists(username)) {
return "用户名已被使用";
}
// 检查邮箱是否已注册
if (FileUtil.emailExists(email)) {
return "该邮箱已被注册";
}
// 生成注册码
String registrationCode = EmailUtil.generateRegistrationCode();
User user = new User(username, email, registrationCode);
// 发送注册码到邮箱
boolean sendSuccess = EmailUtil.sendRegistrationCode(email, username, registrationCode);
if (sendSuccess) {
// 保存用户信息
FileUtil.saveUser(user);
return "注册码已发送到您的邮箱,请查收!";
} else {
return "邮件发送失败,请检查邮箱地址或稍后重试";
try {
validateStringLength(username, "用户名", 2, 20);
validateStringNotEmpty(email, "邮箱");
if (!ValidationUtil.isValidEmail(email)) {
return "邮箱格式不正确";
}
if (FileUtil.usernameExists(username)) {
return "用户名已被使用";
}
if (FileUtil.emailExists(email)) {
return "该邮箱已被注册";
}
String registrationCode = EmailUtil.generateRegistrationCode();
User user = new User(username, email, registrationCode);
boolean sendSuccess = EmailUtil.sendRegistrationCode(email, username, registrationCode);
if (sendSuccess) {
FileUtil.saveUser(user);
logInfo("用户注册成功: " + username);
return "注册码已发送到您的邮箱,请查收!";
} else {
return "邮件发送失败,请检查邮箱地址或稍后重试";
}
} catch (IllegalArgumentException e) {
return e.getMessage();
} catch (Exception e) {
logError("用户注册异常: " + e.getMessage());
return "系统错误,请稍后重试";
}
}
/**
* -
*/
@Override
public String completeRegistration(String username, String code, String password, String confirmPassword) {
User user = FileUtil.loadUserByUsername(username);
if (user == null) {
return "用户不存在或注册码未发送";
}
if (!user.getRegistrationCode().equals(code)) {
return "注册码不正确";
}
if (!password.equals(confirmPassword)) {
return "两次输入的密码不一致";
}
try {
validateStringNotEmpty(username, "用户名");
validateStringNotEmpty(code, "注册码");
validateStringNotEmpty(password, "密码");
validateStringNotEmpty(confirmPassword, "确认密码");
User user = FileUtil.loadUserByUsername(username);
if (user == null) {
return "用户不存在或注册码未发送";
}
if (!user.getRegistrationCode().equals(code)) {
return "注册码不正确";
}
if (!password.equals(confirmPassword)) {
return "两次输入的密码不一致";
}
if (!ValidationUtil.isValidPassword(password)) {
return "密码必须为6-10位且包含大小写字母和数字";
}
user.setPassword(password);
user.setRegistered(true);
FileUtil.saveUser(user);
if (!ValidationUtil.isValidPassword(password)) {
return "密码必须为6-10位且包含大小写字母和数字";
logInfo("用户完成注册: " + username);
return "注册成功!";
} catch (Exception e) {
logError("完成注册异常: " + e.getMessage());
return "系统错误,请稍后重试";
}
user.setPassword(password);
user.setRegistered(true);
FileUtil.saveUser(user);
return "注册成功!";
}
/**
* - 使
*/
@Override
public User login(String loginId, String password) {
// 判断是邮箱还是用户名
User user;
if (loginId.contains("@")) {
// 如果是邮箱格式,按邮箱查找
user = FileUtil.loadUserByEmail(loginId);
} else {
// 否则按用户名查找
user = FileUtil.loadUserByUsername(loginId);
try {
validateStringNotEmpty(loginId, "登录ID");
validateStringNotEmpty(password, "密码");
User user;
if (loginId.contains("@")) {
user = FileUtil.loadUserByEmail(loginId);
} else {
user = FileUtil.loadUserByUsername(loginId);
}
if (user == null) {
logInfo("登录失败: 用户不存在 - " + loginId);
return null;
}
if (user.getPassword() == null || !user.getPassword().equals(password)) {
logInfo("登录失败: 密码错误 - " + loginId);
return null;
}
logInfo("登录成功: " + user.getUsername());
return user;
} catch (Exception e) {
logError("登录异常: " + e.getMessage());
return null;
}
}
// 验证用户
if (user == null) {
return null; // 用户不存在
}
@Override
public String changePassword(User user, String oldPassword, String newPassword, String confirmPassword) {
try {
validateNotNull(user, "用户");
validateStringNotEmpty(oldPassword, "原密码");
validateStringNotEmpty(newPassword, "新密码");
validateStringNotEmpty(confirmPassword, "确认密码");
if (user.getPassword() == null || !user.getPassword().equals(password)) {
return null; // 密码错误
}
if (!user.getPassword().equals(oldPassword)) {
return "原密码不正确";
}
return user; // 登录成功
}
if (!newPassword.equals(confirmPassword)) {
return "两次输入的新密码不一致";
}
/**
*
*/
public String changePassword(User user, String oldPassword, String newPassword, String confirmPassword) {
if (!user.getPassword().equals(oldPassword)) {
return "原密码不正确";
}
if (!ValidationUtil.isValidPassword(newPassword)) {
return "新密码必须为6-10位且包含大小写字母和数字";
}
if (!newPassword.equals(confirmPassword)) {
return "两次输入的新密码不一致";
}
user.setPassword(newPassword);
FileUtil.saveUser(user);
if (!ValidationUtil.isValidPassword(newPassword)) {
return "新密码必须为6-10位且包含大小写字母和数字";
logInfo("密码修改成功: " + user.getUsername());
return "密码修改成功";
} catch (Exception e) {
logError("修改密码异常: " + e.getMessage());
return "系统错误,请稍后重试";
}
user.setPassword(newPassword);
FileUtil.saveUser(user);
return "密码修改成功";
}
@Override
public void cleanupUnregisteredUsers() {
try {
FileUtil.cleanupUnregisteredUsers();
logInfo("执行未注册用户清理");
} catch (Exception e) {
logError("清理未注册用户异常: " + e.getMessage());
}
}
}

@ -0,0 +1,11 @@
package controller;
import model.User;
public interface UserService {
String registerUser(String username, String email);
String completeRegistration(String username, String code, String password, String confirmPassword);
User login(String loginId, String password);
String changePassword(User user, String oldPassword, String newPassword, String confirmPassword);
void cleanupUnregisteredUsers();
}

@ -34,9 +34,11 @@ public class EmailUtil {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.port", SMTP_PORT);
// 超时设置
props.put("mail.smtp.timeout", "10000");
props.put("mail.smtp.connectiontimeout", "10000");
// 创建认证器
Authenticator authenticator = new Authenticator() {
@Override
@ -44,20 +46,25 @@ public class EmailUtil {
return new PasswordAuthentication(FROM_EMAIL, EMAIL_PASSWORD);
}
};
Session session = Session.getInstance(props, authenticator);
try {
// 创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM_EMAIL, FROM_NAME, "UTF-8"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(userEmail));
message.setSubject("数学学习软件 - 注册验证码", "UTF-8");
// 邮件内容HTML格式
String htmlContent = buildEmailContent(username, code);
message.setContent(htmlContent, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
System.out.println("✅ 注册码已成功发送到: " + userEmail);
return true;
} catch (Exception e) {
System.err.println("❌ 邮件发送失败: " + e.getMessage());
e.printStackTrace();
@ -92,7 +99,6 @@ public class EmailUtil {
" <div class=\"code-box\">" +
" <div class=\"code\">" + code + "</div>" +
" </div>" +
" <p>注册码直到系统退出前都有效,请尽快完成注册。</p>" +
" <p>如果这不是您的操作,请忽略此邮件。</p>" +
" <div class=\"footer\">" +
" <p>此为系统邮件,请勿回复</p>" +

@ -24,38 +24,43 @@ public class FileUtil {
static {
new File("data").mkdirs();
}
/**
*
*/
public static void cleanupUnregisteredUsers() {
try {
Map<String, User> users = loadAllUsers();
boolean hasChanges = false;
long currentTime = System.currentTimeMillis();
// 使用迭代器安全删除
Iterator<Map.Entry<String, User>> iterator = users.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, User> entry = iterator.next();
User user = entry.getValue();
// 删除条件:未设置密码 或 未完成注册
if (user.getPassword() == null || user.getPassword().isEmpty() || !user.isRegistered()) {
// 删除条件:未设置密码 或 未完成注册 且 创建时间超过24小时
if ((user.getPassword() == null || user.getPassword().isEmpty() || !user.isRegistered())) {
iterator.remove();
hasChanges = true;
System.out.println("清理未注册用户: " + user.getUsername() + " (" + user.getEmail() + ")");
}
}
if (hasChanges) {
saveAllUsers(users);
System.out.println("未注册用户清理完成");
} else {
System.out.println("没有需要清理的未注册用户");
}
}catch (Exception e) {
} catch (Exception e) {
System.err.println("清理未注册用户时出错: " + e.getMessage());
e.printStackTrace();
}
}
public static void saveAllUsers(Map<String, User> users) {
try (FileWriter writer = new FileWriter(USERS_FILE)) {
gson.toJson(users, writer);
@ -63,6 +68,7 @@ public class FileUtil {
System.err.println("保存用户数据失败: " + e.getMessage());
}
}
// 用户相关方法保持不变...
public static void saveUser(User user) {
try {
@ -150,6 +156,24 @@ public class FileUtil {
}
}
/**
*
*/
public static ExamData loadCurrentExam() {
try {
File file = new File(CURRENT_EXAM_FILE);
if (!file.exists()) {
return null;
}
try (FileReader reader = new FileReader(file)) {
return gson.fromJson(reader, ExamData.class);
}
} catch (IOException e) {
System.err.println("加载试卷失败: " + e.getMessage());
return null;
}
}
/**
*

@ -1,6 +1,7 @@
package view;
import controller.NavigationController;
import controller.NavigationService;
import controller.QuestionController;
import model.Question;
@ -24,6 +25,7 @@ import java.awt.event.ItemListener;
public class ExamView extends JFrame {
private QuestionController questionController;
private NavigationService navigationService;
private JLabel questionLabel;
private JLabel progressLabel;
private ButtonGroup optionGroup;
@ -35,6 +37,7 @@ public class ExamView extends JFrame {
public ExamView() {
questionController = new QuestionController();
navigationService = NavigationController.getInstance();
initializeUI();
}
@ -272,7 +275,7 @@ public class ExamView extends JFrame {
dispose();
// 显示结果页面
NavigationController.showResultView(score, total, percentage);
navigationService.showResultView(score, total, percentage); // 修改
}
}
}

@ -1,7 +1,9 @@
package view;
import controller.NavigationController;
import controller.NavigationService;
import controller.UserController;
import controller.UserService;
import model.User;
import javax.swing.JFrame;
@ -20,18 +22,21 @@ import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginView extends JFrame {
private JTextField usernameField; // 新增:用户名字段
private JTextField usernameField;
private JPasswordField passwordField;
private UserController userController;
private UserService userController;
private NavigationService navigationService;
public LoginView() {
userController = new UserController();
navigationService = NavigationController.getInstance();
initializeUI();
cleanupUnregisteredUsers();
}
private void cleanupUnregisteredUsers() {
try {
userController.cleanuers();
userController.cleanupUnregisteredUsers();
} catch (Exception e) {
System.err.println("清理未注册用户时出错: " + e.getMessage());
}
@ -52,12 +57,12 @@ public class LoginView extends JFrame {
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
mainPanel.add(titleLabel, BorderLayout.NORTH);
// Form panel - 修改为用户名和密码
// Form panel
JPanel formPanel = new JPanel(new GridLayout(3, 2, 10, 10));
JLabel usernameLabel = new JLabel("用户名:"); // 修改:改为用户名
JLabel usernameLabel = new JLabel("用户名:");
usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
usernameField = new JTextField(); // 初始化用户名字段
usernameField = new JTextField();
JLabel passwordLabel = new JLabel("密码:");
passwordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
@ -87,7 +92,8 @@ public class LoginView extends JFrame {
// Add action listeners
loginButton.addActionListener(new LoginAction());
registerButton.addActionListener(e -> {
NavigationController.showRegisterView();
navigationService.showRegisterView();
});
// Enter key support
@ -113,12 +119,12 @@ public class LoginView extends JFrame {
if (user != null) {
JOptionPane.showMessageDialog(LoginView.this,
"登录成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
// 修改:传递用户信息到主界面
NavigationController.showMainView(user);
navigationService.showMainView(user);
} else {
JOptionPane.showMessageDialog(LoginView.this,
"用户名或密码错误", "错误", JOptionPane.ERROR_MESSAGE);
}
}
}
}
}

@ -1,6 +1,7 @@
package view;
import controller.NavigationController;
import controller.NavigationService; // 新增导入
import controller.UserController;
import model.User;
@ -23,9 +24,11 @@ public class MainView extends JFrame {
private JComboBox<String> difficultyComboBox;
private JTextField countField;
private User currentUser; // 保存当前登录用户
private NavigationService navigationService; // 新增
public MainView(User user) {
this.currentUser = user;
this.navigationService = NavigationController.getInstance(); // 新增
initializeUI();
}
@ -86,7 +89,7 @@ public class MainView extends JFrame {
// Add action listeners
startButton.addActionListener(new StartExamAction());
changePasswordButton.addActionListener(new ChangePasswordAction());
logoutButton.addActionListener(e -> NavigationController.showLoginView());
logoutButton.addActionListener(e -> navigationService.showLoginView()); // 修改
add(mainPanel);
}
@ -105,7 +108,7 @@ public class MainView extends JFrame {
return;
}
NavigationController.showExamView(difficulty, count);
navigationService.showExamView(difficulty, count); // 修改
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(MainView.this,
"请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);

@ -1,6 +1,7 @@
package view;
import controller.NavigationController;
import controller.NavigationService;
import controller.UserController;
import model.User;
@ -12,28 +13,33 @@ import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RegisterView extends JFrame {
private JTextField usernameField;
private JTextField usernameField; // 用户名输入框
private JTextField emailField;
private JTextField codeField;
private JPasswordField passwordField;
private JPasswordField confirmPasswordField;
private UserController userController;
private String currentUsername;
private NavigationService navigationService; // 新增
private String currentUsername; // 保存当前注册的用户名
public RegisterView() {
userController = new UserController();
navigationService = NavigationController.getInstance(); // 新增
initializeUI();
}
private void initializeUI() {
setTitle("数学学习软件 - 注册");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(550, 550); // 增加高度以容纳所有组件
setSize(550, 500);
setLocationRelativeTo(null);
setResizable(false);
@ -45,8 +51,8 @@ public class RegisterView extends JFrame {
titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
mainPanel.add(titleLabel, BorderLayout.NORTH);
// Form panel
JPanel formPanel = new JPanel(new GridLayout(6, 2, 10, 10));
// Form panel - 增加用户名字段
JPanel formPanel = new JPanel(new GridLayout(8, 2, 10, 10));
JLabel usernameLabel = new JLabel("用户名:");
usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
@ -80,7 +86,7 @@ public class RegisterView extends JFrame {
formPanel.add(emailLabel);
formPanel.add(emailField);
formPanel.add(sendCodeButton);
formPanel.add(new JLabel()); // 空标签占位
formPanel.add(new JLabel());
formPanel.add(codeLabel);
formPanel.add(codeField);
formPanel.add(passwordLabel);
@ -88,31 +94,17 @@ public class RegisterView extends JFrame {
formPanel.add(confirmPasswordLabel);
formPanel.add(confirmPasswordField);
mainPanel.add(formPanel, BorderLayout.CENTER);
// 创建底部面板,包含密码提示和返回按钮
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
formPanel.add(registerButton);
// 密码要求提示
JLabel hintLabel = new JLabel(
"<html><body style='text-align: center'>" +
"密码要求6-10位必须包含大小写字母和数字<br>" +
"例如Abc123、Test456" +
"</body></html>", JLabel.CENTER);
hintLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
hintLabel.setForeground(Color.GRAY);
bottomPanel.add(hintLabel, BorderLayout.CENTER);
mainPanel.add(formPanel, BorderLayout.CENTER);
// Back button
JButton backButton = new JButton("返回登录");
backButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
backButton.addActionListener(e -> NavigationController.showLoginView());
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(registerButton); // 将注册按钮移到这里
buttonPanel.add(backButton);
bottomPanel.add(buttonPanel, BorderLayout.SOUTH);
backButton.addActionListener(e -> navigationService.showLoginView()); // 修改
JPanel bottomPanel = new JPanel(new FlowLayout());
bottomPanel.add(backButton);
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
// Add action listeners
@ -162,7 +154,7 @@ public class RegisterView extends JFrame {
if (result.equals("注册成功!")) {
JOptionPane.showMessageDialog(RegisterView.this,
result, "成功", JOptionPane.INFORMATION_MESSAGE);
NavigationController.showLoginView();
navigationService.showLoginView(); // 修改
} else {
JOptionPane.showMessageDialog(RegisterView.this,
result, "错误", JOptionPane.ERROR_MESSAGE);

@ -1,6 +1,7 @@
package view;
import controller.NavigationController;
import controller.NavigationService;
import javax.swing.JFrame;
import javax.swing.JPanel;
@ -17,8 +18,10 @@ import java.awt.event.ActionListener;
public class ResultView extends JFrame {
private JLabel scoreLabel;
private JLabel percentageLabel;
private NavigationService navigationService;
public ResultView() {
navigationService = NavigationController.getInstance(); // 新增
initializeUI();
}
@ -63,7 +66,7 @@ public class ResultView extends JFrame {
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
// Add action listeners
continueButton.addActionListener(e -> NavigationController.showMainView());
continueButton.addActionListener(e -> navigationService.showMainView()); // 修改
exitButton.addActionListener(e -> System.exit(0));
add(mainPanel);

Loading…
Cancel
Save