首页 > 数据库 >javaSwing+JDBC+mysql校园跑管理项目(附源码下载)

javaSwing+JDBC+mysql校园跑管理项目(附源码下载)

时间:2024-05-26 15:34:07浏览次数:44  
标签:00 JDBC 06 String 30 add 源码 mysql new

1.数据准备

DELETE
FROM students;
Delete
from running;

INSERT INTO students (student_id, name, age, major, grade)
VALUES (1, '王小明', 20, '计算机科学与技术', '男'),
       (2, '张小红', 21, '软件工程', '女'),
       (3, '李小华', 22, '信息技术', '女'),
       (4, '刘小刚', 23, '电子商务', '男'),
       (5, '陈小丽', 20, '金融学', '女'),
       (6, '杨小强', 21, '市场营销', '男'),
       (7, '赵小云', 22, '国际贸易', '女'),
       (8, '孙小明', 23, '会计学', '男'),
       (9, '周小刚', 20, '人力资源管理', '男'),
       (10, '吴小红', 21, '旅游管理', '女'),
       (11, '郑小华', 22, '汉语言文学', '女'),
       (12, '王小云', 23, '外国语言文学', '女'),
       (13, '黄小明', 20, '历史学', '男'),
       (14, '徐小红', 21, '哲学', '女'),
       (15, '朱小刚', 22, '社会学', '男'),
       (16, '秦小丽', 23, '心理学', '女'),
       (17, '何小明', 20, '统计学', '男'),
       (18, '许小红', 21, '应用数学', '女'),
       (19, '吕小刚', 22, '物理学', '男'),
       (20, '施小丽', 23, '化学', '女'),
       (21, '沈小明', 20, '生物学', '男'),
       (22, '马小红', 21, '地理学', '女'),
       (23, '韩小刚', 22, '地球科学', '男'),
       (24, '顾小丽', 23, '生态学', '女'),
       (25, '侯小明', 20, '环境科学', '男'),
       (26, '邓小红', 21, '农学', '女'),
       (27, '曹小刚', 22, '林学', '男'),
       (28, '丁小丽', 23, '园艺学', '女'),
       (29, '钟小明', 20, '水产养殖学', '男'),
       (30, '苏小红', 21, '海洋科学', '女'),
       (31, '潘小刚', 22, '地球物理学', '男'),
       (32, '董小丽', 23, '大气科学', '女'),
       (33, '蒋小明', 20, '海洋地质学', '男'),
       (34, '余小红', 21, '地质工程', '女'),
       (35, '方小刚', 22, '采矿工程', '男'),
       (36, '石小丽', 23, '石油工程', '女'),
       (37, '雷小明', 20, '矿业工程', '男'),
       (38, '贺小红', 21, '工程管理', '女'),
       (39, '倪小刚', 22, '软件工程', '男'),
       (40, '汤小丽', 23, '电子信息工程', '女'),
       (41, '滕小明', 20, '通信工程', '男'),
       (42, '殷小红', 21, '自动化', '女'),
       (43, '罗小刚', 22, '电气工程', '男'),
       (44, '毕小丽', 23, '建筑学', '女'),
       (45, '郝小明', 20, '城市规划学', '男'),
       (46, '邬小红', 21, '工程造价', '女'),
       (47, '安小刚', 22, '工商管理', '男'),
       (48, '常小丽', 23, '公共管理', '女'),
       (49, '乔小明', 20, '行政管理', '男'),
       (50, '郭小红', 21, '人口学', '女'),
       (51, '梁小刚', 22, '计算机科学与技术', '男'),
       (52, '龚小明', 23, '软件工程', '男'),
       (53, '文小红', 20, '信息技术', '女'),
       (54, '肖小华', 21, '电子商务', '女'),
       (55, '潘小刚', 22, '金融学', '男'),
       (56, '方小红', 23, '市场营销', '女'),
       (57, '韩小云', 20, '国际贸易', '男'),
       (58, '曾小明', 21, '会计学', '男'),
       (59, '黄小红', 22, '人力资源管理', '女'),
       (60, '程小刚', 23, '旅游管理', '男'),
       (61, '谢小华', 20, '汉语言文学', '女'),
       (62, '曹小云', 21, '外国语言文学', '男'),
       (63, '钟小明', 22, '历史学', '女'),
       (64, '彭小红', 23, '哲学', '男'),
       (65, '程小刚', 20, '社会学', '男'),
       (66, '汤小红', 21, '心理学', '女'),
       (67, '施小云', 22, '统计学', '男'),
       (68, '黄小明', 23, '应用数学', '男');


INSERT INTO running(student_id, BKM, YKM, alltime, avgspeed, NOKM)
VALUES (1, 80, 75, '12:30:00', '06:00', 5),
       (2, 65, 60, '10:45:00', '06:45', 5),
       (3, 90, 85, '14:15:00', '05:40', 5),
       (4, 75, 70, '11:30:00', '06:00', 5),
       (5, 70, 65, '11:00:00', '06:30', 5),
       (6, 85, 80, '12:45:00', '06:00', 5),
       (7, 60, 55, '09:30:00', '06:30', 5),
       (8, 95, 90, '15:15:00', '06:00', 5),
       (9, 80, 75, '12:30:00', '06:00', 5),
       (10, 65, 60, '10:45:00', '06:45', 5),
       (11, 90, 85, '14:15:00', '05:40', 5),
       (12, 75, 70, '11:30:00', '06:00', 5),
       (13, 70, 65, '11:00:00', '06:30', 5),
       (14, 85, 80, '12:45:00', '06:00', 5),
       (15, 60, 55, '09:30:00', '06:30', 5),
       (16, 95, 90, '15:15:00', '06:00', 5),
       (17, 80, 75, '12:30:00', '06:00', 5),
       (18, 65, 60, '10:45:00', '06:45', 5),
       (19, 90, 85, '14:15:00', '05:40', 5),
       (20, 75, 70, '11:30:00', '06:00', 5),
       (21, 70, 65, '11:00:00', '06:30', 5),
       (22, 85, 80, '12:45:00', '06:00', 5),
       (23, 60, 55, '09:30:00', '06:30', 5),
       (24, 95, 90, '15:15:00', '06:00', 5),
       (25, 80, 75, '12:30:00', '06:00', 5),
       (26, 65, 60, '10:45:00', '06:45', 5),
       (27, 90, 85, '14:15:00', '05:40', 5),
       (28, 75, 70, '11:30:00', '06:00', 5),
       (29, 70, 65, '11:00:00', '06:30', 5),
       (30, 85, 80, '12:45:00', '06:00', 5),
       (31, 60, 55, '09:30:00', '06:30', 5),
       (32, 95, 90, '15:15:00', '06:00', 5),
       (33, 80, 75, '12:30:00', '06:00', 5),
       (34, 65, 60, '10:45:00', '06:45', 5),
       (35, 90, 85, '14:15:00', '05:40', 5),
       (36, 75, 70, '11:30:00', '06:00', 5),
       (37, 70, 65, '11:00:00', '06:30', 5),
       (38, 85, 80, '12:45:00', '06:00', 5),
       (39, 60, 55, '09:30:00', '06:30', 5),
       (40, 95, 90, '15:15:00', '06:00', 5),
       (41, 80, 75, '12:30:00', '06:00', 5),
       (42, 65, 60, '10:45:00', '06:45', 5),
       (43, 90, 85, '14:15:00', '05:40', 5),
       (44, 75, 70, '11:30:00', '06:00', 5),
       (45, 70, 65, '11:00:00', '06:30', 5),
       (46, 85, 80, '12:45:00', '06:00', 5),
       (47, 60, 55, '09:30:00', '06:30', 5),
       (48, 95, 90, '15:15:00', '06:00', 5),
       (49, 80, 75, '12:30:00', '06:00', 5),
       (50, 65, 60, '10:45:00', '06:45', 5),
       (51, 90, 85, '14:15:00', '05:40', 5),
       (52, 75, 70, '11:30:00', '06:00', 5),
       (53, 70, 65, '11:00:00', '06:30', 5),
       (54, 85, 80, '12:45:00', '06:00', 5),
       (55, 60, 55, '09:30:00', '06:30', 5),
       (56, 95, 90, '15:15:00', '06:00', 5),
       (57, 80, 75, '12:30:00', '06:00', 5),
       (58, 65, 60, '10:45:00', '06:45', 5),
       (59, 90, 85, '14:15:00', '05:40', 5),
       (60, 80, 75, '12:30:00', '06:00', 5),
       (61, 65, 60, '10:45:00', '06:45', 5),
       (62, 90, 85, '14:15:00', '05:40', 5),
       (63, 75, 70, '11:30:00', '06:00', 5),
       (64, 70, 65, '11:00:00', '06:30', 5),
       (65, 85, 80, '12:45:00', '06:00', 5),
       (66, 60, 55, '09:30:00', '06:30', 5),
       (67, 95, 90, '15:15:00', '06:00', 5),
       (68, 80, 75, '12:30:00', '06:00', 5);

2. 项目整体代码结构

3.主程序APP 

单独启动页,主页封装在newmain里面

package GUI;

public class APP {
    public static void main(String[] args) {
        newmain n1 = new newmain();
        n1.newmain1();
    }
}

4.newmain主页代码

package GUI;

import mysql.SqlConnect;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class newmain {
    private ArrayList<student> studentList = new ArrayList<>();
    private DefaultTableModel model = new DefaultTableModel(
            new Object[]{"学生编号", "姓名", "年龄", "专业", "性别", "本学期公里数", "有效公里数", "跑步总时长", "平均配速", "不合格公里数"}, 0
    );
    private JTextArea textArea = new JTextArea();
    JButton queryButton = new JButton("查询");
    private JScrollPane scrollPane = new JScrollPane();
    private JTable table = new JTable(model);
    private JTextField queryField;
    private JComboBox<String> dropdown;
    JButton addButton;
    JButton deleteButton;
    JButton changeButton;
    JFrame frame = new JFrame("智慧东方校园跑管理系统V1.0");

    public void newmain1() {
        int DIALOG_WHITE = 1100;
        int DIALOG_HEIGHT = 600;
        Point point = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        frame.setBounds(point.x - DIALOG_WHITE / 2, point.y - DIALOG_HEIGHT / 2, DIALOG_WHITE, DIALOG_HEIGHT);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setIconImage(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\icon.png").getImage());
        // 设置窗口为全屏模式
        //frame.setUndecorated(true); // 隐藏标题栏和边框
        frame.setVisible(true);
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        // 创建顶部面板,用于显示系统名称
        JPanel topPanel = new JPanel(new GridBagLayout());
        topPanel.setPreferredSize(new Dimension(400, 50));
        topPanel.setBackground(new Color(0, 0, 0, 255)); // 标题行背景色
        JLabel systemLabel = new JLabel("校园跑管理系统");
        GridBagConstraints gbc = new GridBagConstraints();
        // 设置组件在垂直方向上的对齐方式为居中
        gbc.gridy = 0; // 设置组件在网格中的纵向位置为0
        // 添加标签到顶部面板,并应用布局参数
        topPanel.add(systemLabel, gbc);
        systemLabel.setFont(new Font("宋体", Font.BOLD, 20));
        systemLabel.setForeground(Color.WHITE); // 标题文字颜色设置为白色
        topPanel.add(systemLabel);
        mainPanel.add(topPanel, BorderLayout.NORTH);
        frame.add(mainPanel);
        // 创建左侧面板,包含功能列表
        JPanel leftPanel = new JPanel(new GridLayout(10, 1));
        leftPanel.setBackground(new Color(0, 0, 0, 176)); // 左边列背景色
        leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 10, 0)); // 添加边距
        JButton studentButton = new JButton("学生管理");
        studentButton.setForeground(Color.WHITE); // 设置文字颜色为白色
        studentButton.setBackground(new Color(0, 90, 141, 255)); // 设置背景色
        studentButton.setBorderPainted(false); // 不绘制按钮边框
        studentButton.setFocusPainted(false);
        studentButton.setRolloverEnabled(false);
        studentButton.setPressedIcon(null);
        JButton teacherButton = new JButton("教师管理");
        teacherButton.setForeground(Color.WHITE); // 设置文字颜色为白色
        teacherButton.setBackground(new Color(0, 90, 141, 255)); // 设置背景色
        teacherButton.setBorderPainted(false); // 不绘制按钮边框
        teacherButton.setFocusPainted(false);
        teacherButton.setRolloverEnabled(false);
        teacherButton.setPressedIcon(null);
        JButton otherButton = new JButton("其他功能");
        otherButton.setForeground(Color.WHITE);
        otherButton.setBackground(new Color(0, 90, 141, 255));
        otherButton.setBorderPainted(false);
        otherButton.setFocusPainted(false);
        otherButton.setRolloverEnabled(false);
        otherButton.setPressedIcon(null);
        studentButton.setPreferredSize(new Dimension(150, 30));
        teacherButton.setPreferredSize(new Dimension(150, 30));
        otherButton.setPreferredSize(new Dimension(150, 30));
        leftPanel.add(studentButton);
        JLabel label1 = new JLabel();
        Dimension labelSize = new Dimension(label1.getPreferredSize().width, 20);
        leftPanel.add(label1);
        label1.setPreferredSize(labelSize);
        leftPanel.add(teacherButton);
        JLabel label2 = new JLabel();
        Dimension labelSize2 = new Dimension(label1.getPreferredSize().width, 20);
        leftPanel.add(label2);
        label2.setPreferredSize(labelSize2);
        leftPanel.add(otherButton);
        mainPanel.add(leftPanel, BorderLayout.WEST);

        JPanel content = new JPanel();
        CardLayout cardLayout = new CardLayout();
        content.setLayout(cardLayout);
        JPanel studentPanel = new JPanel();
        JPanel tePanel = new JPanel();
        tePanel.add(new JLabel("教师管理界面"));
        JPanel settingsPanel = new JPanel();
        settingsPanel.add(new JLabel("其他"));
        content.add(studentPanel, "stu");
        content.add(tePanel, "te");
        content.add(settingsPanel, "other");
        mainPanel.add(content, BorderLayout.CENTER);
        studentButton.addActionListener(
                new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        cardLayout.show(content, "stu");
                    }
                }
        );
        teacherButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(content, "te");
            }
        });
        otherButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(content, "other");
            }
        });

        //学生管理界面
        JPanel topsearch = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        queryField = new JTextField();
        queryField.setPreferredSize(new Dimension(200, 27));
        queryField.setBorder(null);
        addButton = new JButton("添加");
        deleteButton = new JButton("删除");
        changeButton = new JButton("修改");
        changeButton(addButton);
        changeButton(deleteButton);
        changeButton(queryButton);
        changeButton(changeButton);
        String[] options = {"姓名", "学号", "专业", "年龄", "性别"};
        dropdown = new JComboBox<>(options);
        dropdown.setBorder(BorderFactory.createEmptyBorder());
        dropdown.setSelectedIndex(1);
        dropdown.setPrototypeDisplayValue("Thisaaaa");
        // dropdown.setOpaque(false);
        topsearch.add(dropdown);
        topsearch.add(queryField);
        topsearch.add(queryButton);
        topsearch.add(addButton);
        topsearch.add(deleteButton);
        topsearch.add(changeButton);
        caozuo();
        studentPanel.add(topsearch, BorderLayout.NORTH);
        scrollPane.add(table);
        scrollPane.setPreferredSize(new Dimension(1000, 500)); // 设置滚动面板的首选大小
        scrollPane.setViewportView(table);
        studentPanel.add(scrollPane, BorderLayout.CENTER);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH); // 最大化窗口
    }

    public void caozuo() {
        //添加业务
        addButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                add a1 = new add();
                a1.addWindow();
            }
        });
        //删除
        deleteButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    deletestu();
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        //修改
        changeButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row == -1) {
                    JOptionPane.showMessageDialog(
                            frame, // 父组件,如果为 null,则弹窗会显示在屏幕中央
                            "当前没有选中任何行", // 提示消息
                            "提示", // 标题
                            JOptionPane.INFORMATION_MESSAGE // 提示类型,这里使用信息类型
                    );
                } else {
                    change ch1 = new change();
                    ch1.changeWindow(table);
                }

            }
        });
        //查询
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                search();
            }
        });
    }

    private void deletestu() throws SQLException {
        int result = showConfirmDeleteDialog();
        if (result == JOptionPane.YES_OPTION) {
            // 用户确认删除,执行相应的操作
            SqlConnect s1 = new SqlConnect();
            Connection conn = SqlConnect.getConnection();
            int row = table.getSelectedRow();
            int click = (int) table.getValueAt(row, 0);
            String sql = "DELETE FROM students WHERE student_id =" + click;
            String sql1 = "DELETE FROM running WHERE student_id =" + click;
            PreparedStatement pst = conn.prepareStatement(sql);
            PreparedStatement pst1 = conn.prepareStatement(sql1);
            pst.executeUpdate();
            pst1.executeUpdate();
            queryButton.doClick();
            clearAll3(conn, pst, pst1);
        }
    }

    public static int showConfirmDeleteDialog() {
        // 显示确认删除的对话框,并返回用户的选择
        return JOptionPane.showConfirmDialog(null, "确认删除选中的行?", "确认删除", JOptionPane.YES_NO_OPTION);
    }

    public void changeButton(JButton Button) {
        Button.setBorderPainted(false); // 不绘制按钮边框
        Button.setFocusPainted(false);
        Button.setRolloverEnabled(false);
        Button.setPressedIcon(null);
        Button.setForeground(Color.WHITE); // 设置文字颜色为白色
        Button.setBackground(new Color(0, 90, 141, 255)); // 设置背景色
    }

    public void newmodel(JTable table) {
        model = new DefaultTableModel(
                new Object[]{"学生编号", "姓名", "年龄", "专业", "性别", "本学期公里数", "有效公里数", "跑步总时长", "平均配速", "不合格公里数"}, 0
        );
        table.setModel(model);
    }

    public void search() {
        String selectedItem = (String) dropdown.getSelectedItem();
        SqlConnect s1 = new SqlConnect();
        Connection conn = SqlConnect.getConnection();
        String type = null;
        switch (selectedItem) {
            case "学号":
                type = "student_id";
                break;
            case "姓名":
                type = "name";
                break;
            case "专业":
                type = "major";
                break;
            case "年龄":
                type = "age";
                break;
            case "性别":
                type = "grade";
                break;
        }
        //select *from students join running r on students.student_id = r.student_id where students.student_id = 1;
        String sql = "select * from students join running on students.student_id = running.student_id where students." + type + " = ?";
        try {
            newmodel(table);//模型清除面板数据
            String text = queryField.getText();
            if (text == null) {
                System.out.println("数据不能为空");
                return;
            }
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1, text);
            System.out.println(text + type);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                student stu = new student();
                int id = rs.getInt(1);
                String name = rs.getString(2);
                int age = rs.getInt(3);
                String major = rs.getString(4);
                String gender = rs.getString(5);
                stu.setAge(age);
                stu.setName(name);
                stu.setGrade(gender);
                stu.setMajor(major);
                stu.setStudent_id(id);
                studentList.add(stu);
                System.out.println("查询成功");
                System.out.println(studentList);
                for (student student : studentList) {
                    model.addRow(new Object[]{student.getStudent_id(), student.getName(), student.getAge(), student.getMajor(), student.getGrade()});
                }
                studentList.clear();
            }
            clearAll1(conn, pst, rs);
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

    private void clearAll1(Connection conn, PreparedStatement pst, ResultSet rs) throws SQLException {
        conn.close();
        pst.close();
        rs.close();
        System.out.println("资源释放成功");
    }

    private void clearAll2(Connection conn, PreparedStatement pst) throws SQLException {
        conn.close();
        pst.close();
        System.out.println("资源释放成功");
    }

    private void clearAll3(Connection conn, PreparedStatement pst, PreparedStatement pst2) throws SQLException {
        conn.close();
        pst.close();
        pst2.close();
        System.out.println("资源释放成功");
    }
}

将swing的页面和功能代码分开编写,更清晰直观,方便后续调用,封装了按钮美化和释放资源函数。 其中的icon图片地址自己找图片并修改地址。

 5.数据库启动函数

package mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库连接得到conn对象
 */
public class SqlConnect {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/campusrunmanagementsystem?useSSL=false";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    public SqlConnect() {
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            System.out.println("提示:数据库连接成功~");
        } catch (ClassNotFoundException e) {
            System.err.println(e.getMessage());
        } catch (SQLException e) {
            System.err.println("异常:数据库连接失败!");
        }
        return conn;
    }
}

返回一个conn对象便于后续调用,这里注意的是MySQL的配置信息改为自己的。 

6.数据添加页面

package GUI;

import mysql.SqlConnect;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

class add extends JFrame {
    private List<JTextField> textFieldList = new ArrayList<>();

    public void addWindow() {
        JFrame frame = new JFrame("添加学生信息");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        int DIALOG_WHITE = 600;//宽度
        int DIALOG_HEIGHT = 600;//高度
        Point point = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        frame.setBounds(point.x - DIALOG_WHITE / 2, point.y - DIALOG_HEIGHT / 2, DIALOG_WHITE, DIALOG_HEIGHT);
        frame.setVisible(true);
        frame.setIconImage(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\icon.png").getImage());
        String[] list = {"学生编号", "学生姓名", "年龄", "专业", "性别"};
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(15, 15, 15, 15); // 设置组件之间的间距
        // 插入六行
        for (int i = 0; i < 5; i++) {
            JLabel label = new JLabel(list[i]);
            JTextField textField = new JTextField(20);
            textFieldList.add(textField);
            textField.setBorder(null);
            textField.setPreferredSize(new Dimension(200, 30)); // 设置文本框大小为200x30
            textField.setMargin(new Insets(5, 5, 5, 5));
            // 添加标签和文本框到主容器中
            gbc.gridy = i;
            mainPanel.add(label, gbc);
            gbc.gridx = 1;
            mainPanel.add(textField, gbc);
            // 重置横向位置
            gbc.gridx = 0;
        }
        JButton confirmButton = new JButton("确定");
        confirmButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int count = addstu();
                    if (count > 0) {
                        frame.setVisible(false);
                        JOptionPane.showMessageDialog(
                                frame, // 父组件,如果为 null,则弹窗会显示在屏幕中央
                                "添加成功,数据已更新", // 提示消息
                                "提示", // 标题
                                JOptionPane.INFORMATION_MESSAGE // 提示类型,这里使用信息类型
                        );
                    } else {
                        frame.setVisible(false);
                        JOptionPane.showMessageDialog(
                                frame, // 父组件,如果为 null,则弹窗会显示在屏幕中央
                                "添加失败", // 提示消息
                                "提示", // 标题
                                JOptionPane.INFORMATION_MESSAGE // 提示类型,这里使用信息类型
                        );
                    }
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }

            }
        });

        changeButton(confirmButton);

        gbc.gridx = 1;
        gbc.gridy = 5; // 最后一行
        gbc.anchor = GridBagConstraints.LAST_LINE_END; // 设置对齐方式为最后一行的右下角
        mainPanel.add(confirmButton, gbc);
        // 将主容器添加到窗口中
        frame.add(mainPanel);
    }

    private int addstu() throws SQLException {
        SqlConnect s1 = new SqlConnect();
        Connection conn = SqlConnect.getConnection();
        String sql = "INSERT INTO students(student_id, name, age, major, grade) values (?,?,?,?,?)";
        String sql2 = "insert into running(student_id, BKM, YKM, alltime, avgspeed, NOKM) values (?, null, null, null, null, null);";
        PreparedStatement pst = conn.prepareStatement(sql);
        PreparedStatement pst2 = conn.prepareStatement(sql2);
        pst.setInt(1, Integer.parseInt(textFieldList.get(0).getText()));
        pst.setString(2, textFieldList.get(1).getText());
        pst.setInt(3, Integer.parseInt(textFieldList.get(2).getText()));
        pst.setString(4, textFieldList.get(3).getText());
        pst.setString(5, textFieldList.get(4).getText());
        pst2.setInt(1, Integer.parseInt(textFieldList.get(0).getText()));
        int count = pst.executeUpdate() + pst2.executeUpdate();
        return count;
    }

    public void changeButton(JButton Button) {
        Button.setBorderPainted(false); // 不绘制按钮边框
        Button.setFocusPainted(false);
        Button.setRolloverEnabled(false);
        Button.setPressedIcon(null);
        Button.setForeground(Color.WHITE); // 设置文字颜色为白色
        Button.setBackground(new Color(0, 90, 141, 255)); // 设置背景色
    }
}

7.数据修改页面

package GUI;

import mysql.SqlConnect;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

class change extends JFrame {
    List<JTextField> textFieldList = new ArrayList<>();
    newmain n1 = new newmain();

    public void changeWindow(JTable table) {
        JFrame frame = new JFrame("修改学生信息");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        int DIALOG_WHITE = 600;//宽度
        int DIALOG_HEIGHT = 600;//高度
        Point point = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        frame.setBounds(point.x - DIALOG_WHITE / 2, point.y - DIALOG_HEIGHT / 2, DIALOG_WHITE, DIALOG_HEIGHT);
        frame.setVisible(true);
        frame.setIconImage(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\icon.png").getImage());
        String[] list = {"学生编号", "学生姓名", "年龄", "专业", "性别", "本学期公里数"};
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(15, 15, 15, 15); // 设置组件之间的间距
        // 插入六行
        for (int i = 0; i < 6; i++) {
            JLabel label = new JLabel(list[i]);
            JTextField textField = new JTextField(20);
            textFieldList.add(textField);
            textField.setBorder(null);
            textField.setPreferredSize(new Dimension(200, 30)); // 设置文本框大小为200x30
            textField.setMargin(new Insets(5, 5, 5, 5));
            // 添加标签和文本框到主容器中
            gbc.gridy = i;
            mainPanel.add(label, gbc);
            gbc.gridx = 1;
            mainPanel.add(textField, gbc);
            // 重置横向位置
            gbc.gridx = 0;
        }
        JButton confirmButton = new JButton("确定");
        add a1 = new add();
        a1.changeButton(confirmButton);
        int row = table.getSelectedRow();
// 获取id并设置文本框的值
        Object idObj = table.getValueAt(row, 0);
        int id = idObj != null ? (int) idObj : 0;
        textFieldList.get(0).setText(String.valueOf(id));

// 获取name并设置文本框的值
        Object nameObj = table.getValueAt(row, 1);
        String name = nameObj != null ? (String) nameObj : "";
        textFieldList.get(1).setText(name);

// 获取age并设置文本框的值
        Object ageObj = table.getValueAt(row, 2);
        int age = ageObj != null ? (int) ageObj : 0;
        textFieldList.get(2).setText(String.valueOf(age));

// 获取major并设置文本框的值
        Object majorObj = table.getValueAt(row, 3);
        String major = majorObj != null ? (String) majorObj : "";
        textFieldList.get(3).setText(major);

// 获取gender并设置文本框的值
        Object genderObj = table.getValueAt(row, 4);
        String gender = genderObj != null ? (String) genderObj : "";
        textFieldList.get(4).setText(gender);

// 获取KM并设置文本框的值
        Object KMObj = table.getValueAt(row, 5);
        int KM = KMObj != null ? (int) KMObj : 0;
        textFieldList.get(5).setText(String.valueOf(KM));

        confirmButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    SqlConnect s1 = new SqlConnect();
                    Connection conn = SqlConnect.getConnection();
                    String sql = "UPDATE students set student_id =?,name=?,age=?,major=?,grade=? where student_id=" + id;
                    //String sql1 = "UPDATE running set YKM = ? where student_id=" + id;
                    PreparedStatement pst = conn.prepareStatement(sql);
                    //PreparedStatement pst1 = conn.prepareStatement(sql1);
                    pst.setInt(1, Integer.parseInt(textFieldList.get(0).getText()));
                    pst.setString(2, textFieldList.get(1).getText());
                    pst.setInt(3, Integer.parseInt(textFieldList.get(2).getText()));
                    pst.setString(4, textFieldList.get(3).getText());
                    pst.setString(5, textFieldList.get(4).getText());
                    //pst1.setInt(1, Integer.parseInt(textFieldList.get(0).getText()));
                    int count = pst.executeUpdate();
                    System.out.println(count);
                    frame.setVisible(false);
                    JOptionPane.showMessageDialog(
                            frame, // 父组件,如果为 null,则弹窗会显示在屏幕中央
                            "修改成功,数据已更新", // 提示消息
                            "提示", // 标题
                            JOptionPane.INFORMATION_MESSAGE // 提示类型,这里使用信息类型
                    );
                } catch (SQLException ex) {
                    frame.setVisible(false);
                    JOptionPane.showMessageDialog(
                            frame, // 父组件,如果为 null,则弹窗会显示在屏幕中央
                            "修改失败,请联系管理员", // 提示消息
                            "提示", // 标题
                            JOptionPane.INFORMATION_MESSAGE // 提示类型,这里使用信息类型
                    );
                    throw new RuntimeException(ex);
                }
            }
        });
        gbc.gridx = 1;
        gbc.gridy = 6; // 最后一行
        gbc.anchor = GridBagConstraints.LAST_LINE_END; // 设置对齐方式为最后一行的右下角
        mainPanel.add(confirmButton, gbc);
        // 将主容器添加到窗口中
        frame.add(mainPanel);
    }
}

8.学生实体类

package GUI;

public class student {
    private int student_id;
    private String name;
    private int age;
    private String major;
    private String grade;

    public student(int student_id, String name, int age, String major, String grade) {
        this.student_id = student_id;
        this.name = name;
        this.age = age;
        this.major = major;
        this.grade = grade;
    }

    public student() {
    }

    public int getStudent_id() {
        return student_id;
    }

    public void setStudent_id(int student_id) {
        this.student_id = student_id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    @Override
    public String toString() {
        return "student{" +
                "student_id=" + student_id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", major='" + major + '\'' +
                ", grade='" + grade + '\'' +
                '}';
    }
}

9.总结 

该项目为期末项目,用时一天半,制作较为粗糙,仅能实现基本的增删改查,且本人对swing界面编写十分生疏,本文仅供参考,欢迎各位留言指正。

百度网盘提取链接:

https://pan.baidu.com/s/16k2i_6dC35z76P0i5FmwAA?pwd=1234 

标签:00,JDBC,06,String,30,add,源码,mysql,new
From: https://blog.csdn.net/zhnxb/article/details/139215030

相关文章

  • docker下安装mysql,并实现主从复制
    1mysql的安装与启动1.1拉取mysql5.7的镜像dockerpullmysql:5.71.2运行dockerrun:运行Docker容器的命令。--restart=always:指定容器在退出时总是重新启动。这意味着,无论容器是正常退出还是异常退出,Docker将自动重新启动这个容器。--privileged=true:......
  • 【计算机毕业设计】基于SSM+Vue的校园美食交流系统【源码+lw+部署文档】
    目录前 言第1章概述1.1研究背景1.2研究目的1.3研究内容      第二章开发技术介绍2.1Java技术2.2Mysql数据库2.3B/S结构2.4SSM框架第三章系统分析3.1可行性分析3.1.1 技术可行性3.1.2经济可行性3.1.3操作可行性3.2系统性能分析3.3......
  • 【计算机毕业设计】基于SSM+Vue的新能源汽车在线租赁管理系统【源码+lw+部署文档】
    摘 要随着科学技术的飞速发展,社会的方方面面、各行各业都在努力与现代的先进技术接轨,通过科技手段来提高自身的优势,新能源汽车在线租赁当然也不能排除在外。新能源汽车在线租赁是以实际运用为开发背景,运用软件工程开发方法,采用SSM技术构建的一个管理系统。整个开发过程首先......
  • 【python】python 全国5A级景区数据采集与pyecharts可视化(源码+数据+论文)【独一无二】
    ......
  • 成为MySQL DBA后,再看ORACLE数据库(一、安装与启动)
    一、前言ORACLE作为世界上最牛逼的关系型数据库,也是我从事数据库行业入门学习的数据库,记得当时学习ORACLE数据库时就深感其复杂性,对很多概念一知半解、似懂非懂,当ORACLE管理员期间也遇到过不少问题,不过好在有ORACLE原厂工程师驻场,基本上问题都能解决。后来因为领导的安排和工作的......
  • 省钱兄科技:优质JAVA源码,实惠交易
    省钱兄科技:优质JAVA源码,实惠交易的不二之选在当今的信息化时代,软件开发已成为企业发展的重要驱动力。而在软件开发的过程中,选择高质量的源码是确保项目成功的基础。省钱兄科技,凭借其优质的JAVA源码和实惠的交易模式,成为了众多开发者和企业的首选合作伙伴。一、优质JAVA源码,铸......
  • MySQL-存储引擎
    MySQL体系结构1).连接层最上层是一些客户端和链接服务,包含本地sock通信和大多数基于客户端/服务端工具实现的类似于TCP/IP的通信。2).服务层第二层架构主要完成大多数的核心服务功能,如SQL接口,并完成缓存的查询,SQL的分析和优化,部分内置函数的执行......
  • Mysql-约束
    约束概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据。目的:保证数据库中数据的正确、有效性和完整性。约束演示:外键约束左侧的emp表是员工表,里面存储员工的基本信息,包含员工的ID、姓名、年龄、职位、薪资、入职日期、上级主管ID、部门ID,在员......
  • Vue3实战笔记(45)—VUE3封装一些echarts常用的组件,附源码
    文章目录前言一、柱状图框选二、折线图堆叠总结前言日前使用hooks的方式封装组件,在我使用复杂的图标时候遇到了些问题,预想在onMounted中初始化echarts,在使用hooks的时候,组件没有渲染完,使用实例会出现各种各样的问题,并且在hooks中使用一些外部属性也属实遇到了些麻烦......
  • 2024web网页源码大学生网页设计制作作业实例代码 (全网最全,建议收藏) HTML+CSS+JS
    文章目录......