import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.*; import java.awt.*; import java.sql.*; import java.util.List; import java.util.ArrayList; import javax.swing.table.DefaultTableModel; import org.jfree.chart.*; import org.jfree.chart.plot.*; import org.jfree.data.category.DefaultCategoryDataset; import java.io.*; import java.text.DecimalFormat;
// 主类 public class student {
public static void main(String[] args) { // 创建 JFrame 实例 JFrame frame = new JFrame("Login Example"); // Setting the width and height of frame frame.setSize(350, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* 创建面板,这个类似于 HTML 的 div 标签 * 我们可以创建多个面板并在 JFrame 中指定位置 * 面板中我们可以添加文本字段,按钮及其他组件。 */ JPanel panel = new JPanel(); // 添加面板 frame.add(panel); /* * 调用用户定义的方法并添加组件到面板 */ placeComponents(panel);
// 设置界面可见 frame.setVisible(true); }
private static void placeComponents(JPanel panel) {
/* 布局部分我们这边不多做介绍 * 这边设置布局为 null */ panel.setLayout(null);
// 创建 JLabel JLabel userLabel = new JLabel("User:"); /* 这个方法定义了组件的位置。 * setBounds(x, y, width, height) * x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。 */ userLabel.setBounds(10,20,80,25); panel.add(userLabel);
/* * 创建文本域用于用户输入 */ JTextField userText = new JTextField(20); userText.setBounds(100,20,165,25); panel.add(userText);
// 输入密码的文本域 JLabel passwordLabel = new JLabel("Password:"); passwordLabel.setBounds(10,50,80,25); panel.add(passwordLabel);
/* *这个类似用于输入的文本域 * 但是输入的信息会以点号代替,用于包含密码的安全性 */ JPasswordField passwordText = new JPasswordField(20); passwordText.setBounds(100,50,165,25); panel.add(passwordText);
// 创建登录按钮 JButton loginButton = new JButton("login"); loginButton.setBounds(10, 80, 80, 25); panel.add(loginButton); }
}
class StudentGradeManagementSystem { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("学生成绩管理系统"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1000, 800); frame.add(new MainPanel()); frame.setLocationRelativeTo(null); frame.setVisible(true); }); } }
// 主面板 class MainPanel extends JPanel { public MainPanel() { ImageIcon originalIcon = new ImageIcon("C:\\Users\\ASUS\\Desktop\\微信图片_20241031205640.jpg"); Image scaledImage = originalIcon.getImage().getScaledInstance(980, 800, Image.SCALE_SMOOTH); // 根据需要调整大小 JLabel background = new JLabel(new ImageIcon(scaledImage)); background.setLayout(new BorderLayout());
JButton btnStudentLogin = new JButton("学生登录"); JButton btnTeacherLogin = new JButton("教师登录"); JButton btnAdminLogin = new JButton("管理员登录");
btnStudentLogin.addActionListener(e -> studentLogin()); btnTeacherLogin.addActionListener(e -> teacherLogin()); btnAdminLogin.addActionListener(e -> adminLogin());
add(btnStudentLogin); add(btnTeacherLogin); add(btnAdminLogin); add(background, BorderLayout.CENTER); }
private void studentLogin() { login("学生", this::showStudentFeatures); }
private void teacherLogin() { login("教师", this::showTeacherFeatures); }
private void adminLogin() { login("管理员", this::showAdminFeatures); }
private void login(String role, LoginCallback callback) { JTextField idField = new JTextField(15); JPasswordField passwordField = new JPasswordField(15); JPanel loginPanel = new JPanel(new GridLayout(0, 1)); loginPanel.add(new JLabel("ID:")); loginPanel.add(idField); loginPanel.add(new JLabel("密码:")); loginPanel.add(passwordField);
int option = JOptionPane.showConfirmDialog(this, loginPanel, role + "登录", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { String id = idField.getText(); String password = new String(passwordField.getPassword()); callback.showFeatures(id, password); } }
private void showStudentFeatures(String studentId, String password) { // 此处可以添加学生验证逻辑 JFrame studentFrame = new JFrame("学生功能"); studentFrame.setSize(500, 400); studentFrame.add(new StudentPanel(studentId)); // 传递学生ID studentFrame.setLocationRelativeTo(null); studentFrame.setVisible(true); }
private void showTeacherFeatures(String teacherId, String password) { // 此处可以添加教师验证逻辑 JFrame teacherFrame = new JFrame("教师功能"); teacherFrame.setSize(600, 400); teacherFrame.add(new TeacherPanel()); teacherFrame.setLocationRelativeTo(null); teacherFrame.setVisible(true); }
private void showAdminFeatures(String adminId, String password) { // 此处可以添加管理员验证逻辑 JFrame adminFrame = new JFrame("管理员功能"); adminFrame.setSize(600, 400); adminFrame.add(new AdminPanel()); adminFrame.setLocationRelativeTo(null); adminFrame.setVisible(true); }
interface LoginCallback { void showFeatures(String id, String password); } }
/// 学生功能面板 class StudentPanel extends JPanel { private String studentId;
public StudentPanel(String studentId) { this.studentId = studentId; setLayout(new BorderLayout()); // 使用 BorderLayout 布局
// 1. 学生信息区顶部标题 JPanel topPanel = new JPanel(); JLabel titleLabel = new JLabel("学生管理功能面板", JLabel.CENTER); titleLabel.setFont(new Font("Serif", Font.BOLD, 20)); topPanel.add(titleLabel); add(topPanel, BorderLayout.NORTH);
// 2. 添加学生头像或其他图片 ImageIcon studentImageIcon = new ImageIcon("C:\\Users\\ASUS\\Desktop\\微信图片_20241031111338.jpg"); Image studentImage = studentImageIcon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH); JLabel studentImageLabel = new JLabel(new ImageIcon(studentImage)); JPanel imagePanel = new JPanel(); // 创建一个单独的面板来显示图片 imagePanel.add(studentImageLabel); imagePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // 添加边框
// 3. 功能按钮面板 JPanel buttonPanel = new JPanel(new GridLayout(3, 1, 10, 10)); // 3行1列的布局 JButton btnViewGrades = createStyledButton("查询成绩"); JButton btnViewProfile = createStyledButton("查看个人资料"); JButton btnViewCourses = createStyledButton("查看课程信息");
// 按钮事件绑定 btnViewGrades.addActionListener(e -> queryGrades()); btnViewProfile.addActionListener(e -> viewProfile()); btnViewCourses.addActionListener(e -> viewCourses());
// 添加按钮到按钮面板 buttonPanel.add(btnViewGrades); buttonPanel.add(btnViewProfile); buttonPanel.add(btnViewCourses);
// 4. 底部版权信息 JPanel bottomPanel = new JPanel(); bottomPanel.setBackground(new Color(72, 61, 139)); JLabel bottomLabel = new JLabel("版权所有 © 2024 学生管理系统"); bottomLabel.setForeground(Color.WHITE); bottomPanel.add(bottomLabel);
// 将图片面板、按钮面板和版权信息加入到主面板 add(imagePanel, BorderLayout.WEST); // 把图片放在左侧 add(buttonPanel, BorderLayout.CENTER); // 把按钮放在中间 add(bottomPanel, BorderLayout.SOUTH); // 把版权信息放在底部 }
private JButton createStyledButton(String text) { JButton button = new JButton(text); button.setFont(new Font("Serif", Font.PLAIN, 18)); // 使用Serif字体,字号18 button.setFocusPainted(false); // 不显示按钮的焦点框 button.setPreferredSize(new Dimension(200, 60)); // 设置按钮的大小 button.setForeground(Color.BLACK); // 文字颜色为黑色 button.setBackground(Color.WHITE); // 背景为白色 button.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // 边框颜色为黑色 return button; } // 查询成绩的方法 private void queryGrades() { try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM studentgrade WHERE stuid2 = ?")) {
stmt.setString(1, studentId); ResultSet rs = stmt.executeQuery(); StringBuilder grades = new StringBuilder("成绩查询:\n");
while (rs.next()) { grades.append(rs.getString("name")).append("\n") .append("高数:").append(rs.getInt("math")).append(",") .append("马原:").append(rs.getInt("MaYuan")).append(";") .append("英语:").append(rs.getInt("English")).append(",") .append("线性代数:").append(rs.getInt("linemath")).append("\n"); }
JOptionPane.showMessageDialog(this, grades.toString()); } } catch (ClassNotFoundException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "JDBC 驱动未找到: " + e.getMessage()); } catch (SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); } }
private void viewProfile() { try { // 加载数据库驱动 Class.forName("com.mysql.cj.jdbc.Driver");
// 建立连接(根据实际情况修改数据库连接信息) try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", // 数据库连接 "root", // 用户名 "1405269390a")) { // 密码
// SQL 查询:根据 studentId 查询该学生的个人信息 String query = "SELECT stuid1, name, telenumber, qqmail, classnumber FROM student WHERE stuid1 = ?"; try (PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, studentId); // 设置查询条件为学生ID
// 执行查询并获取结果 ResultSet rs = stmt.executeQuery();
if (rs.next()) { // 获取查询结果 String stuid = rs.getString("stuid1"); String name = rs.getString("name"); String telenumber = rs.getString("telenumber"); String qqmail = rs.getString("qqmail"); String classnumber = rs.getString("classnumber");
// 构建学生个人资料字符串 String studentProfile = "学生姓名: " + name + "\n" + "学号: " + stuid + "\n" + "电话: " + telenumber + "\n" + "QQ邮箱: " + qqmail + "\n" + "班级号: " + classnumber;
// 显示学生资料 JOptionPane.showMessageDialog(this, studentProfile, "个人资料", JOptionPane.INFORMATION_MESSAGE); } else { // 如果未找到该学生的信息 JOptionPane.showMessageDialog(this, "未找到该学生的个人信息。", "错误", JOptionPane.ERROR_MESSAGE); } } }
} catch (ClassNotFoundException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "JDBC 驱动未找到: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } catch (SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } }
// 查看课程信息 private void viewCourses() { // 这里可以添加逻辑查询学生的课程信息 String courses = "已选课程:\n1. 高等数学\n2. 线性代数\n3. 英语\n4. 马原"; JOptionPane.showMessageDialog(this, courses, "课程信息", JOptionPane.INFORMATION_MESSAGE); } }
class TeacherPanel extends JPanel {
public TeacherPanel() { setLayout(new BorderLayout());
// 1. 教师功能区顶部标题 JPanel topPanel = new JPanel(); JLabel titleLabel = new JLabel("教师管理功能界面", JLabel.CENTER); titleLabel.setFont(new Font("Serif", Font.BOLD, 20)); topPanel.add(titleLabel); add(topPanel, BorderLayout.NORTH);
// 2. 创建功能按钮面板 JPanel buttonPanel = new JPanel(new GridLayout(3, 2, 20, 20)); // 按钮布局:3行2列
JButton btnEnterGrades = createStyledButton("录入成绩"); JButton btnModifyGrades = createStyledButton("修改成绩"); JButton btnAnalyzeGrades = createStyledButton("成绩统计分析"); JButton btnViewGrades = createStyledButton("查看成绩"); JButton btnDeleteGrades = createStyledButton("删除成绩"); JButton btnExportGrades = createStyledButton("导出成绩");
// 按钮事件绑定 btnEnterGrades.addActionListener(e -> enterGrades()); btnModifyGrades.addActionListener(e -> modifyGrades()); btnAnalyzeGrades.addActionListener(e -> analyzeGrades()); btnViewGrades.addActionListener(e -> viewGrades()); btnDeleteGrades.addActionListener(e -> deleteGrades()); btnExportGrades.addActionListener(e -> exportGrades());
buttonPanel.add(btnEnterGrades); buttonPanel.add(btnModifyGrades); buttonPanel.add(btnAnalyzeGrades); buttonPanel.add(btnViewGrades); buttonPanel.add(btnDeleteGrades); buttonPanel.add(btnExportGrades);
add(buttonPanel, BorderLayout.CENTER);
// 3. 底部版权信息 JPanel bottomPanel = new JPanel(); bottomPanel.setBackground(new Color(72, 61, 139)); JLabel bottomLabel = new JLabel("版权所有 © 2024 教师管理系统"); bottomLabel.setForeground(Color.WHITE); bottomPanel.add(bottomLabel); add(bottomPanel, BorderLayout.SOUTH); }
private JButton createStyledButton(String text) { JButton button = new JButton(text); button.setFont(new Font("Serif", Font.PLAIN, 18)); // 使用Serif字体,字号18 button.setFocusPainted(false); // 不显示按钮的焦点框 button.setPreferredSize(new Dimension(200, 60)); // 设置按钮的大小 button.setForeground(Color.BLACK); // 文字颜色为黑色 button.setBackground(Color.WHITE); // 背景为白色 button.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // 边框颜色为黑色 return button; }
// 录入成绩功能 private void enterGrades() { JTextField studentIdField = new JTextField(15); JTextField mathField = new JTextField(15); JTextField maYuanField = new JTextField(15); JTextField englishField = new JTextField(15); JTextField lineMathField = new JTextField(15);
JPanel panel = new JPanel(new GridLayout(0, 1)); panel.add(new JLabel("学生ID:")); panel.add(studentIdField); panel.add(new JLabel("数学成绩:")); panel.add(mathField); panel.add(new JLabel("MaYuan成绩:")); panel.add(maYuanField); panel.add(new JLabel("英语成绩:")); panel.add(englishField); panel.add(new JLabel("线性代数成绩:")); panel.add(lineMathField);
int option = JOptionPane.showConfirmDialog(this, panel, "录入成绩", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { String studentId = studentIdField.getText(); int mathScore = Integer.parseInt(mathField.getText()); int maYuanScore = Integer.parseInt(maYuanField.getText()); int englishScore = Integer.parseInt(englishField.getText()); int lineMathScore = Integer.parseInt(lineMathField.getText());
saveGrades(studentId, mathScore, maYuanScore, englishScore, lineMathScore); } }
// 保存成绩到数据库 private void saveGrades(String studentId, int mathScore, int maYuanScore, int englishScore, int lineMathScore) { try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); PreparedStatement stmt = conn.prepareStatement("INSERT INTO studentgrade (stuid2, math, MaYuan, English, linemath) VALUES (?, ?, ?, ?, ?)")) { stmt.setString(1, studentId); stmt.setInt(2, mathScore); stmt.setInt(3, maYuanScore); stmt.setInt(4, englishScore); stmt.setInt(5, lineMathScore); stmt.executeUpdate(); JOptionPane.showMessageDialog(this, "成绩录入成功!"); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); } }
// 查看成绩 private void viewGrades() { String studentId = JOptionPane.showInputDialog(this, "请输入学生ID:"); try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM studentgrade WHERE stuid2 = ?")) { stmt.setString(1, studentId); ResultSet rs = stmt.executeQuery(); if (rs.next()) { String result = String.format("学生ID: %s\n数学: %d\n马原: %d\n英语: %d\n线性代数: %d", rs.getString("stuid2"), rs.getInt("math"), rs.getInt("MaYuan"), rs.getInt("English"), rs.getInt("linemath")); JOptionPane.showMessageDialog(this, result); } else { JOptionPane.showMessageDialog(this, "未找到学生ID!"); } } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); } }
// 修改成绩 private void modifyGrades() { String studentId = JOptionPane.showInputDialog(this, "请输入学生ID:"); JTextField newMathField = new JTextField(15); JTextField newMaYuanField = new JTextField(15); JTextField newEnglishField = new JTextField(15); JTextField newlineField = new JTextField(15);
JPanel panel = new JPanel(new GridLayout(0, 1)); panel.add(new JLabel("新数学成绩:")); panel.add(newMathField); panel.add(new JLabel("新马原成绩:")); panel.add(newMaYuanField); panel.add(new JLabel("新英语成绩:")); panel.add(newEnglishField); panel.add(new JLabel("新线性代数成绩:")); panel.add(newlineField);
int option = JOptionPane.showConfirmDialog(this, panel, "修改成绩", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { int newMathScore = Integer.parseInt(newMathField.getText()); int newMaYuanScore = Integer.parseInt(newMaYuanField.getText()); updateGrades(studentId, newMathScore, newMaYuanScore); } }
// 更新成绩 private void updateGrades(String studentId, int newMathScore, int newMaYuanScore) { try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); PreparedStatement stmt = conn.prepareStatement("UPDATE studentgrade SET math = ?, MaYuan = ? WHERE stuid2 = ?")) { stmt.setInt(1, newMathScore); stmt.setInt(2, newMaYuanScore); stmt.setString(3, studentId); int rowsUpdated = stmt.executeUpdate(); if (rowsUpdated > 0) { JOptionPane.showMessageDialog(this, "成绩修改成功!"); } else { JOptionPane.showMessageDialog(this, "未找到对应的学生ID!"); } } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); } }
// 删除成绩 private void deleteGrades() { String studentId = JOptionPane.showInputDialog(this, "请输入学生ID:"); try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); PreparedStatement stmt = conn.prepareStatement("DELETE FROM studentgrade WHERE stuid2 = ?")) { stmt.setString(1, studentId); int rowsDeleted = stmt.executeUpdate(); if (rowsDeleted > 0) { JOptionPane.showMessageDialog(this, "成绩删除成功!"); } else { JOptionPane.showMessageDialog(this, "未找到对应的学生ID!"); } } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); } }
// 导出成绩 private void exportGrades() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("选择导出文件位置"); int userChoice = fileChooser.showSaveDialog(this); if (userChoice == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); if (!file.getName().endsWith(".csv")) { file = new File(file.getAbsolutePath() + ".csv"); } try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write("学生ID,学生姓名,数学,马原,英语,线性代数\n");
try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT stuid2, name, math, MaYuan, English, linemath FROM studentgrade"); while (rs.next()) { String stuid2 = rs.getString("stuid2"); String name = rs.getString("name"); int math = rs.getInt("math"); int MaYuan = rs.getInt("MaYuan"); int English = rs.getInt("English"); int linemath = rs.getInt("linemath");
DecimalFormat df = new DecimalFormat("#"); String formattedMath = df.format(math); String formattedMaYuan = df.format(MaYuan); String formattedEnglish = df.format(English); String formattedLinemath = df.format(linemath);
writer.write(String.format("%s,%s,%s,%s,%s,%s\n", stuid2, name, formattedMath, formattedMaYuan, formattedEnglish, formattedLinemath)); } JOptionPane.showMessageDialog(this, "成绩导出成功!"); } catch (SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); } } catch (ClassNotFoundException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库驱动类未找到: " + e.getMessage()); } } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "文件写入错误: " + e.getMessage()); } } }
// 成绩统计分析
private void analyzeGrades() { try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); Statement stmt = conn.createStatement()) {
// 查询每门课程的平均分、最高分和最低分 String query = "SELECT " + "AVG(math) AS avg_math, MAX(math) AS max_math, MIN(math) AS min_math, " + "AVG(MaYuan) AS avg_maYuan, MAX(MaYuan) AS max_maYuan, MIN(MaYuan) AS min_maYuan, " + "AVG(English) AS avg_english, MAX(English) AS max_english, MIN(English) AS min_english, " + "AVG(linemath) AS avg_linemath, MAX(linemath) AS max_linemath, MIN(linemath) AS min_linemath " + "FROM studentgrade";
ResultSet rs = stmt.executeQuery(query); if (rs.next()) { // 显示成绩信息 String message = String.format( "数学:平均分: %.2f, 最高分: %d, 最低分: %d\n" + "马原:平均分: %.2f, 最高分: %d, 最低分: %d\n" + "英语:平均分: %.2f, 最高分: %d, 最低分: %d\n" + "线性代数:平均分: %.2f, 最高分: %d, 最低分: %d", rs.getDouble("avg_math"), rs.getInt("max_math"), rs.getInt("min_math"), rs.getDouble("avg_maYuan"), rs.getInt("max_maYuan"), rs.getInt("min_maYuan"), rs.getDouble("avg_english"), rs.getInt("max_english"), rs.getInt("min_english"), rs.getDouble("avg_linemath"), rs.getInt("max_linemath"), rs.getInt("min_linemath") );
JOptionPane.showMessageDialog(this, message);
// 询问用户是否生成图表 int response = JOptionPane.showConfirmDialog(this, "是否生成成绩图表?", "选择图表类型", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.YES_OPTION) { // 选择图表类型 String[] options = {"柱状图", "折线图"}; int chartType = JOptionPane.showOptionDialog(this, "请选择图表类型:", "选择图表类型", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
// 创建数据集 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(rs.getDouble("avg_math"), "平均分", "数学"); dataset.addValue(rs.getInt("max_math"), "最高分", "数学"); dataset.addValue(rs.getInt("min_math"), "最低分", "数学"); dataset.addValue(rs.getDouble("avg_maYuan"), "平均分", "马原"); dataset.addValue(rs.getInt("max_maYuan"), "最高分", "马原"); dataset.addValue(rs.getInt("min_maYuan"), "最低分", "马原"); dataset.addValue(rs.getDouble("avg_english"), "平均分", "英语"); dataset.addValue(rs.getInt("max_english"), "最高分", "英语"); dataset.addValue(rs.getInt("min_english"), "最低分", "英语"); dataset.addValue(rs.getDouble("avg_linemath"), "平均分", "线性代数"); dataset.addValue(rs.getInt("max_linemath"), "最高分", "线性代数"); dataset.addValue(rs.getInt("min_linemath"), "最低分", "线性代数");
// 创建图表 JFreeChart chart; if (chartType == 0) { // 柱状图 chart = ChartFactory.createBarChart( "成绩分析", "课程", "分数", dataset, PlotOrientation.VERTICAL, true, true, false ); } else { // 折线图 chart = ChartFactory.createLineChart( "成绩分析", "课程", "分数", dataset, PlotOrientation.VERTICAL, true, true, false ); }
// 显示图表 ChartFrame frame = new ChartFrame("成绩分析图", chart); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); } } }
//实现管理员的方法,默认语言就是中文,但是整体的公共的语言没有改变。
class AdminPanel extends JPanel { private String currentTheme = "默认主题"; // 默认主题 private String currentLanguage = "中文"; // 默认语言 private String currentDatabaseURL = "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC"; private String currentDatabaseUsername = "root"; private String currentDatabasePassword = "1405269390a"; public AdminPanel() { setLayout(new BorderLayout());
// 顶部标题 JPanel topPanel = new JPanel(); JLabel titleLabel = new JLabel("管理员控制面板", JLabel.CENTER); titleLabel.setFont(new Font("Serif", Font.BOLD, 24)); topPanel.add(titleLabel); add(topPanel, BorderLayout.NORTH);
// 功能按钮面板 JPanel buttonPanel = new JPanel(new GridLayout(3, 6, 5, 5)); // 3列布局
JButton btnUserManagement = createStyledButton("学生管理"); JButton btnSystemSettings = createStyledButton("系统设置"); JButton btnGenerateReport = createStyledButton("生成报表");
// 按钮事件绑定 btnUserManagement.addActionListener(e -> manageUsers()); btnSystemSettings.addActionListener(e -> systemSettings()); btnGenerateReport.addActionListener(e -> generateReport());
// 添加按钮到按钮面板 buttonPanel.add(btnUserManagement); buttonPanel.add(btnSystemSettings); buttonPanel.add(btnGenerateReport);
add(buttonPanel, BorderLayout.CENTER);
// 底部版权信息 JPanel bottomPanel = new JPanel(); bottomPanel.setBackground(new Color(72, 61, 139)); JLabel bottomLabel = new JLabel("版权所有 © 2024 管理员系统", JLabel.CENTER); bottomLabel.setForeground(Color.WHITE); bottomPanel.add(bottomLabel); add(bottomPanel, BorderLayout.SOUTH); }
private JButton createStyledButton(String text) { JButton button = new JButton(text); button.setFont(new Font("Serif", Font.PLAIN, 18)); // 使用Arial字体,较大的字号 button.setFocusPainted(false); // 不显示按钮的焦点框 button.setPreferredSize(new Dimension(10, 10)); // 设置按钮的大小 button.setForeground(Color.BLACK); // 文字颜色为黑色 button.setBackground(Color.WHITE); // 背景为白色 button.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2)); // 边框颜色为黑色 button.setOpaque(false); // 设置按钮背景透明 return button; }
private void manageUsers() { String[] options = {"添加学生", "删除学生", "查看学生"}; int choice = JOptionPane.showOptionDialog(this, "请选择操作:", "学生管理", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
switch (choice) { case 0: // 添加用户 addUser(); break; case 1: // 删除用户 deleteUser(); break; case 2: // 查看用户 viewUsers(); break; default: break; } }
private void addUser() { JTextField usernameField = new JTextField(15); JTextField nameField = new JTextField(15); JPanel panel = new JPanel(new GridLayout(0, 1)); panel.add(new JLabel("学生ID:")); panel.add(usernameField); panel.add(new JLabel("姓名:")); panel.add(nameField);
int option = JOptionPane.showConfirmDialog(this, panel, "添加学生", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { String username = usernameField.getText(); String name = nameField.getText(); saveUserToDatabase(username, name); } }
private void saveUserToDatabase(String username, String name) { try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); PreparedStatement stmt = conn.prepareStatement("INSERT INTO student (stuid1, name) VALUES (?, ?)")) {
stmt.setString(1, username); stmt.setString(2, name); stmt.executeUpdate();
JOptionPane.showMessageDialog(this, "学生 " + name + " 添加成功!"); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); } }
private void deleteUser() { String username = JOptionPane.showInputDialog(this, "请输入要删除的学生ID:"); if (username != null && !username.trim().isEmpty()) { deleteUserFromDatabase(username); } }
private void deleteUserFromDatabase(String studentId) { Connection conn = null; PreparedStatement stmt1 = null, stmt2 = null, stmt3 = null;
try { Class.forName("com.mysql.cj.jdbc.Driver");
// 创建数据库连接 conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a");
// 禁用自动提交,启用事务 conn.setAutoCommit(false);
// 删除学生成绩 String deleteGradesQuery = "DELETE FROM studentgrade WHERE stuid2 = ?"; stmt1 = conn.prepareStatement(deleteGradesQuery); stmt1.setString(1, studentId); stmt1.executeUpdate();
// 删除学生基本信息 String deleteStudentQuery = "DELETE FROM student WHERE stuid1 = ?"; stmt3 = conn.prepareStatement(deleteStudentQuery); stmt3.setString(1, studentId); int rowsAffected = stmt3.executeUpdate();
// 如果成功删除学生信息,提交事务 if (rowsAffected > 0) { conn.commit(); // 提交事务 JOptionPane.showMessageDialog(this, "学生 " + studentId + " 的所有信息删除成功!"); } else { // 如果没有删除学生记录,回滚事务 conn.rollback(); JOptionPane.showMessageDialog(this, "未找到学生 " + studentId + " 的信息。"); } } catch (ClassNotFoundException | SQLException e) { try { if (conn != null) { conn.rollback(); // 出现异常时回滚事务 } } catch (SQLException ex) { ex.printStackTrace(); } e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } finally { try { // 关闭数据库连接和Statement if (stmt1 != null) stmt1.close(); if (stmt2 != null) stmt2.close(); if (stmt3 != null) stmt3.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
private void viewUsers() { List<String> users = fetchUsersFromDatabase(); if (users.isEmpty()) { JOptionPane.showMessageDialog(this, "没有用户记录"); } else { JOptionPane.showMessageDialog(this, String.join("\n", users)); } }
private List<String> fetchUsersFromDatabase() { List<String> users = new ArrayList<>(); try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT stuid1, name FROM student")) {
while (rs.next()) { String studentId = rs.getString("stuid1"); String name = rs.getString("name"); users.add("ID: " + studentId + " | 姓名: " + name); } } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); } return users; }
private void systemSettings() { String[] options = {"设置主题", "设置语言", "修改数据库连接", "返回"}; int choice = JOptionPane.showOptionDialog(this, "选择操作", "系统设置", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
switch (choice) { case 0: setTheme(); break; case 1: setLanguage(); break; case 2: setDatabaseConnection(); // 新增数据库连接设置 break; case 3: default: break; // 返回或关闭 } }
// 设置主题 private void setTheme() { String[] themes = {"默认主题", "暗黑主题", "明亮主题"}; String selectedTheme = (String) JOptionPane.showInputDialog(this, "选择主题", "设置主题", JOptionPane.QUESTION_MESSAGE, null, themes, currentTheme); if (selectedTheme != null) { currentTheme = selectedTheme; applyTheme(); JOptionPane.showMessageDialog(this, "主题已更改为: " + currentTheme); } }
// 应用主题 private void applyTheme() { switch (currentTheme) { case "暗黑主题": setBackground(Color.DARK_GRAY); break; case "明亮主题": setBackground(Color.LIGHT_GRAY); break; default: setBackground(Color.WHITE); break; } repaint(); // 更新界面 }
//设置语言,要更新的是整体阿代码,但是这个并没有实现,有点差错 private void setLanguage() { String[] languages = {"中文", "英文"}; String selectedLanguage = (String) JOptionPane.showInputDialog(this, "选择语言", "设置语言", JOptionPane.QUESTION_MESSAGE, null, languages, currentLanguage); if (selectedLanguage != null) { currentLanguage = selectedLanguage;
// 根据语言设置字体 Font newFont; if (currentLanguage.equals("英文")) { newFont = new Font("Arial", Font.PLAIN, 12); } else { newFont = new Font("SimSun", Font.PLAIN, 18); // 使用中文字体 }
// 设置整个应用程序的字体 setComponentsFont(this, newFont);
JOptionPane.showMessageDialog(this, "语言已更改为: " + currentLanguage); } }
private void setComponentsFont(Component component, Font font) { if (component instanceof JLabel) { ((JLabel) component).setFont(font); } else if (component instanceof JTextField) { ((JTextField) component).setFont(font); } else if (component instanceof JTextArea) { ((JTextArea) component).setFont(font); } else if (component instanceof JTable) { ((JTable) component).setFont(font); } else if (component instanceof Container) { Component[] subComponents = ((Container) component).getComponents(); for (Component subComponent : subComponents) { setComponentsFont(subComponent, font); } } }
// 修改数据库连接 private void setDatabaseConnection() { String url = JOptionPane.showInputDialog(this, "输入数据库URL", currentDatabaseURL); if (url != null && !url.trim().isEmpty()) { currentDatabaseURL = url;
// 假设你还有用户名和密码需要设置 String username = JOptionPane.showInputDialog(this, "输入数据库用户名", currentDatabaseUsername); if (username != null) { currentDatabaseUsername = username;
String password = JOptionPane.showInputDialog(this, "输入数据库密码", currentDatabasePassword); if (password != null) { currentDatabasePassword = password;
// 这里可以添加连接数据库的代码 // connectToDatabase(currentDatabaseURL, currentDatabaseUsername, currentDatabasePassword);
JOptionPane.showMessageDialog(this, "数据库连接已更改为:\n" + "URL: " + currentDatabaseURL + "\n" + "用户名: " + currentDatabaseUsername); } } } }
private void generateReport() { String reportType = JOptionPane.showInputDialog(this, "请输入报表类型(例如:学生成绩, 学生列表):"); if (reportType != null && !reportType.trim().isEmpty()) { if (reportType.equalsIgnoreCase("学生成绩")) { generateGradeReport(); } else if (reportType.equalsIgnoreCase("学生列表")) { generateUserReport(); } else { JOptionPane.showMessageDialog(this, "无效的报表类型!"); } } }
private void generateGradeReport() { String[] columnNames = {"学生ID", "姓名", "数学成绩", "英语成绩", "MaYuan成绩", "linemath成绩"}; DefaultTableModel model = new DefaultTableModel(columnNames, 0);
try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT stuid2, name, math, English, MaYuan, linemath FROM studentgrade")) {
while (rs.next()) { String studentId = rs.getString("stuid2"); String name = rs.getString("name"); int mathScore = rs.getInt("math"); int englishScore = rs.getInt("English"); int maYuanScore = rs.getInt("MaYuan"); int lineMathScore = rs.getInt("linemath"); model.addRow(new Object[]{studentId, name, mathScore, englishScore, maYuanScore, lineMathScore}); } } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); return; }
JTable table = new JTable(model); JScrollPane scrollPane = new JScrollPane(table); JOptionPane.showMessageDialog(this, scrollPane, "学生成绩报表", JOptionPane.INFORMATION_MESSAGE); }
private void generateUserReport() { String[] columnNames = {"学生ID", "姓名", "电话", "QQ邮箱", "班级编号"}; DefaultTableModel model = new DefaultTableModel(columnNames, 0);
try { Class.forName("com.mysql.cj.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "1405269390a"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT stuid1, name, telenumber, qqmail, classnumber FROM student")) {
while (rs.next()) { String studentId = rs.getString("stuid1"); String name = rs.getString("name"); String telephone = rs.getString("telenumber"); String qqMail = rs.getString("qqmail"); String classNumber = rs.getString("classnumber"); model.addRow(new Object[]{studentId, name, telephone, qqMail, classNumber}); } } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage()); return; }
JTable table = new JTable(model); JScrollPane scrollPane = new JScrollPane(table); JOptionPane.showMessageDialog(this, scrollPane, "用户列表报表", JOptionPane.INFORMATION_MESSAGE); }
}
|