java实验:职员管理系统

代码展示:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new LoginFrame());//使用Swing库中的SwingUtilities类的invokeLater方法来安排在事件调度线程上执行一个任务。
    }
}

class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;

    public LoginFrame() {
        setTitle("员工信息管理系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());

        // Create components
        JLabel usernameLabel = new JLabel("帐号:");
        usernameField = new JTextField( 15);

        JLabel passwordLabel = new JLabel("密码:");
        passwordField = new JPasswordField( 15);

        JButton loginButton = new JButton("登录");
        JButton resetButton = new JButton("重置");

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(usernameLabel, gbc);//用户名标签

        gbc.gridx = 1;
        add(usernameField, gbc);//用户名输入框

        gbc.gridx = 0;
        gbc.gridy = 1;
        add(passwordLabel, gbc);//密码标签

        gbc.gridx = 1;
        add(passwordField, gbc);//密码输入框

        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        add(loginButton, gbc);//登录按钮

        gbc.gridy = 3;
        add(resetButton, gbc);//重置按钮

        // Add action listeners
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());

                // Simple validation (replace with actual validation logic)
                if ("这里填你自己的账号".equals(username) && "这里填你自己的密码".equals(password)) {
                    JOptionPane.showMessageDialog(LoginFrame.this, "登录成功");
                    // Proceed to the main application window
                    new EmployeeManagementSystem();
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(LoginFrame.this, "帐号或密码错误");
                }
            }
        });
        //为清除添加事件监听器
        resetButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                usernameField.setText("");
                passwordField.setText("");
            }
        });

        // Set frame properties
        setSize(500, 500);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

class EmployeeManagementSystem extends JFrame {
    private JTextField searchField;
    private JTable table;
    private DefaultTableModel tableModel;

    private JTextField nameField;
    private JComboBox<String> genderComboBox;
    private JTextField ageField;
    private JTextField salaryField;
    private JComboBox<String> departmentComboBox;//下拉列表框
    private JTextField idField;//一个文本输入框,输id

    private Connection connection;//一个数据库连接对象连接数据库

    public EmployeeManagementSystem() {
        setTitle("员工管理系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗口关闭时为退出程序
        setLayout(new BorderLayout());//设置窗口布局为边界布局

        initializeDatabaseConnection();//初始化数据库连接

        JPanel searchPanel = new JPanel();//创建一个搜索面板,有搜索框,搜索按钮,清楚按钮
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchPanel.add(searchField);
        searchPanel.add(searchButton);
        JButton clearButton = new JButton("清除");
        searchPanel.add(clearButton);

        String[] columnNames = {"员工编号", "姓名", "性别", "年龄", "工资", "部门"};
        tableModel = new DefaultTableModel(columnNames, 0);
        table = new JTable(tableModel);//创建一个表格,用上边的表格模型


        loadDataFromDatabase();//将数据库中的数据加载到表格中


        JPanel inputPanel = new JPanel(new GridLayout(8, 2));
        inputPanel.setBorder(BorderFactory.createTitledBorder("员工信息:"));//创建输入面板,来输入员工相关信息

        inputPanel.add(new JLabel("员工编号:"));
        idField = new JTextField();
        inputPanel.add(idField);

        inputPanel.add(new JLabel("姓名:"));
        nameField = new JTextField();
        inputPanel.add(nameField);

        inputPanel.add(new JLabel("性别:"));
        genderComboBox = new JComboBox<>(new String[]{"男", "女"});
        inputPanel.add(genderComboBox);

        inputPanel.add(new JLabel("年龄:"));
        ageField = new JTextField();
        inputPanel.add(ageField);

        inputPanel.add(new JLabel("工资:"));
        salaryField = new JTextField();
        inputPanel.add(salaryField);

        inputPanel.add(new JLabel("部门:"));
        departmentComboBox = new JComboBox<>(new String[]{"人事部", "技术部", "销售部"});
        inputPanel.add(departmentComboBox);


        JButton addButton = new JButton("新增员工");
        inputPanel.add(addButton);

        //将搜索面板,表格,输入面板添加到窗口中
        add(searchPanel, BorderLayout.NORTH);
        add(new JScrollPane(table), BorderLayout.CENTER);
        add(inputPanel, BorderLayout.EAST);

        //创建一个按钮面板
        JPanel buttonsPanel = new JPanel();
        JButton deleteButton = new JButton("删除员工");
        JButton modifyButton = new JButton("修改信息");
        buttonsPanel.add(deleteButton);
        buttonsPanel.add(modifyButton);
        //吧按钮面板加到窗口中
        add(buttonsPanel, BorderLayout.SOUTH);

        //新增员工按钮的监听器,实现添加员工信息到数据库
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addEmployeeToDatabase();
                loadDataFromDatabase();
            }
        });
        //删除员工按钮的监听器
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteEmployeeFromDatabase();
                loadDataFromDatabase();
            }
        });
        //修改信息按钮的监听器
        modifyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateEmployeeInDatabase();
                loadDataFromDatabase();
            }
        });
        //搜索按钮的监听器
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchEmployeeInDatabase();
            }
        });
        //清除按钮的
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clearSearchResults();
            }
        });



        setSize(800, 600);
        setLocationRelativeTo(null);
        setVisible(true);
    }

//下边是连接数据库的过程
    private void initializeDatabaseConnection() {
        try {

            String url = "jdbc:mysql://127.0.0.1:3306/EmployeeManagement?serverTimezone=UTC";//这里的EmployManagenment是可以改的,你自己创建的数据库名字是什么这就填什么
            String user = "用户名";//数据库的用户名
            String password = "密码";//数据库密码

            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    private void loadDataFromDatabase() {
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM 员工表");


            tableModel.setRowCount(0);//清空表格模型行数


            while (rs.next()) {
                Object[] row = {
                        rs.getString("员工编号"),
                        rs.getString("姓名"),
                        rs.getString("性别"),
                        rs.getInt("年龄"),
                        rs.getDouble("工资"),
                        rs.getString("部门")
                };
                tableModel.addRow(row);//将这些数据添加到表格模型中
            }
        } catch (SQLException e) {
            e.printStackTrace();//发生异常,打印异常堆栈信息
        }
    }

    //这是添加操作
    private void addEmployeeToDatabase() {
        if (idField.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "员工编号不能为空");
            return;
        }
        if (nameField.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "姓名不能为空");
            return;
        }
        if (ageField.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "年龄不能为空");
            return;
        }
        if (salaryField.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "工资不能为空");
            return;
        }
        try {
            String query = "INSERT INTO 员工表 (员工编号, 姓名, 性别, 年龄, 工资, 部门) VALUES (?, ?, ?, ?, ?, ?)";
            PreparedStatement pstmt = connection.prepareStatement(query);
            pstmt.setString(1, idField.getText());
            pstmt.setString(2, nameField.getText());
            pstmt.setString(3, (String) genderComboBox.getSelectedItem());
            pstmt.setInt(4, Integer.parseInt(ageField.getText()));
            pstmt.setDouble(5, Double.parseDouble(salaryField.getText()));
            pstmt.setString(6, (String) departmentComboBox.getSelectedItem());
            pstmt.executeUpdate();//执行sql语句,把这些信息插入到数据库中
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //这是删除操作
    private void deleteEmployeeFromDatabase() {
        try {
            int selectedRow = table.getSelectedRow();//获取表格中选中的行号
            if (selectedRow == -1) {//如果没有选中有效行
                JOptionPane.showMessageDialog(null, "请选择要删除的员工");
                return;
            }
                String employeeId = (String) tableModel.getValueAt(selectedRow, 0);//获取员工行中的员工编号
                String query = "DELETE FROM 员工表 WHERE 员工编号 = ?";
                PreparedStatement pstmt = connection.prepareStatement(query);
                pstmt.setString(1, employeeId);
                pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //
    private void updateEmployeeInDatabase() {
        try {
            int selectedRow = table.getSelectedRow();//还是获取表格中选中的行号
            if (selectedRow != -1) {
                String employeeId = (String) tableModel.getValueAt(selectedRow, 0);
                if (employeeId != null && !employeeId.trim().isEmpty()) {
                    String query = "UPDATE 员工表 SET ";//定义sql更新语句
                    boolean hasPreviousField = false;

                    String name = nameField.getText().trim();//获取姓名字段的值,再判断是否为空
                    if (!name.isEmpty()) {
                        query += "姓名 = ?";
                        hasPreviousField = true;
                    }


                    String gender = (String) genderComboBox.getSelectedItem();
                    if (!gender.isEmpty()) {
                        if (hasPreviousField) query += ", ";
                        query += "性别 = ?";
                        hasPreviousField = true;
                    }

                    String ageText = ageField.getText().trim();
                    if (!ageText.isEmpty()) {
                        if (hasPreviousField) query += ", ";
                        query += "年龄 = ?";
                        hasPreviousField = true;
                    }

                    String salaryText = salaryField.getText().trim();
                    if (!salaryText.isEmpty()) {
                        if (hasPreviousField) query += ", ";
                        query += "工资 = ?";
                        hasPreviousField = true;
                    }

                    String department = (String) departmentComboBox.getSelectedItem();
                    if (!department.isEmpty()) {
                        if (hasPreviousField) query += ", ";
                        query += "部门 = ?";
                    }

                    query += " WHERE 员工编号 = ?";//添加where子句,指定要更新的员工编号

                    PreparedStatement pstmt = connection.prepareStatement(query);
                    int parameterIndex = 1;

                    if (!name.isEmpty()) {
                        pstmt.setString(parameterIndex++, name);
                    }


                    if (!gender.isEmpty()) {
                        pstmt.setString(parameterIndex++, gender);
                    }

                    if (!ageText.isEmpty()) {
                        try {
                            int age = Integer.parseInt(ageText);
                            pstmt.setInt(parameterIndex++, age);
                        } catch (NumberFormatException e) {
                            JOptionPane.showMessageDialog(this, "年龄必须是整数!");
                            return;
                        }
                    }

                    if (!salaryText.isEmpty()) {
                        try {
                            double salary = Double.parseDouble(salaryText);
                            pstmt.setDouble(parameterIndex++, salary);
                        } catch (NumberFormatException e) {
                            JOptionPane.showMessageDialog(this, "工资必须是有效的数字!");
                            return;
                        }
                    }

                    if (!department.isEmpty()) {
                        pstmt.setString(parameterIndex++, department);
                    }

                    pstmt.setString(parameterIndex, employeeId);
                    pstmt.executeUpdate();

                    JOptionPane.showMessageDialog(this, "员工信息更新成功!");
                } else {
                    JOptionPane.showMessageDialog(this, "请选择有效的员工!");
                }
            } else {
                JOptionPane.showMessageDialog(this, "请先选择一个员工!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    private void searchEmployeeInDatabase() {
        try {
            String searchText = searchField.getText().trim();//获取搜索这个框中的文本
            if (searchText.isEmpty()) {//若为空,则弹出提示框
                JOptionPane.showMessageDialog(this, "请输入员工编号或姓名进行搜索!");
                return;
            }

            String query = "SELECT * FROM 员工表 WHERE 员工编号 = ? OR 姓名 LIKE ?";
            PreparedStatement pstmt = connection.prepareStatement(query);//使用连接对象创建一个预处理语句对象
            pstmt.setString(1, searchText);//设置预处理语句中的参数值
            pstmt.setString(2, "%" + searchText + "%");
            ResultSet rs = pstmt.executeQuery();


            boolean found = false;
            while (rs.next()) {//遍历搜索结果

                tableModel.insertRow(0, new Object[]{
                        rs.getString("员工编号"),
                        rs.getString("姓名"),
                        rs.getString("性别"),
                        rs.getInt("年龄"),
                        rs.getDouble("工资"),
                        rs.getString("部门")
                });
                found = true;
            }


            if (found) {
                tableModel.insertRow(1, new Object[]{"----", "----", "----", "----", "----", "----", "----"});
            }

            if (!found) {
                JOptionPane.showMessageDialog(this, "未找到匹配的员工信息!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    private void clearSearchResults() {

        int rowCount = tableModel.getRowCount();//还是获取模型表格的行数

        for (int i = 0; i < rowCount; i++) {
            if (tableModel.getValueAt(i, 0).equals("----")) {//如果当前的第一个单元格为这个符号

                for (int j = i; j >= 0; j--) {//向上遍历,删除每一行
                    tableModel.removeRow(j);
                }
                break;
            }
        }
    }
}

运行结果展示:

登录成功提示:

这里的重置按钮是清空账号密码所填的内容

登陆失败提示:

登陆成功后的界面:

可以在这个界面实现增删改查功能

增:

删:

点中想要删除的那一行然后点击删除员工即可删除

改:

查:

这里我用的是分隔符将查到的信息分隔开

  • 10
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值