背景

本文是《Java Swing GUi从小白到大神》系列最后一篇,前面5篇讲了Swing的基础知识,本篇是对前面知识的综合应用,做一个小的项目实战通讯录系统,以巩固所学知识。若想系统学习请点击首篇博文学习。

项目实战——通讯录系统

文章概览

  1. 通讯录系统软件架构
  2. 通讯录系统界面设计
  3. 通讯录系统功能实现
  4. 通讯录系统代码详解

1. 通讯录系统软件架构

graph TD
    A[登录窗口] --> B[主菜单窗口]
    B --> C[同学通讯录]
    B --> D[同事通讯录]
    B --> E[朋友通讯录]
    B --> F[查询系统]
    B --> H[帮助系统]
graph TD
    C[同学通讯录] --> I[同学基本信息模块]
    C --> J[同学联系方式模块]
    D[同事通讯录] --> K[同事基本信息模块]
    D --> L[同事联系方式模块]
graph TD
    E[朋友通讯录] --> M[朋友基本信息模块]
    E --> N[朋友联系方式模块]
    F[查询系统] --> O[同学查询系统]
    F --> P[同事查询系统]
    F --> Q[朋友查询系统]
    H[帮助系统] --> R[版本信息系统]
    H --> S[帮助文档系统]

2. 通讯录系统界面设计

图片

3. 通讯录系统功能实现

界面包含同学、同事、朋友、查询、帮助模块,提供基本功能,包括添加、修改、删除、查询、帮助等。后端采用mySQL数据库,采用JDBC连接,实现数据持久化。

4. 通讯录系统代码详解

1. 系统类介绍

系统共设计了27个类,共3个表,其中表classmatecompanyfriend为数据表,其他均为UI界面。

2. 代码详解

1. 同学相关类
同学类:ClassMate.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
public class ClassMate {
    private String name;
    private String sex;
    private String address;
    private String homephone;
    private String city;
    private String company;
    private String duty;
    private String salary;
    private String contact;
    private String homeaddress;

    public ClassMate(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getHomephone() {
        return homephone;
    }

    public void setHomephone(String homephone) {
        this.homephone = homephone;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getDuty() {
        return duty;
    }

    public void setDuty(String duty) {
        this.duty = duty;
    }

    public String getSalary() {
        return salary;
    }

    public void setSalary(String salary) {
        this.salary = salary;
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    public String getHomeaddress() {
        return homeaddress;
    }

    public void setHomeaddress(String homeaddress) {
        this.homeaddress = homeaddress;
    }

    @Override
    public String toString() {
        return "ClassMate [name=" + name + ", sex=" + sex + ", address=" + address + ", homephone=" + homephone
                + ", city=" + city + ", company=" + company + ", duty=" + duty + ", salary=" + salary + ", contact="
                + contact + ", homeaddress=" + homeaddress + "]";
    }
}
同学信息面板:ClassMateInfo.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
public ClassMateInfo() {
        this.setLayout(new java.awt.GridBagLayout());

        // 创建 DefaultComboBoxModel
        DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();

        // 创建标题
        JLabel titleLabel = new JLabel("同学基本信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20)); // 设置字体和大小
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

        JLabel[] labels = {
                new JLabel("姓名"), new JLabel("性别"), new JLabel("居住地址"),
                new JLabel("家庭地址"), new JLabel("所在城市"),
                new JLabel("所在公司"), new JLabel("职务"), new JLabel("薪水")
        };

        // 创建 JTextField 和 JComboBox
        nameinput = new JComboBox<String>(model);
        sexyinput = new JTextField(15);
        addressinput = new JTextField(15);
        homeaddressinput = new JTextField(15);
        cityinput = new JTextField(15);
        companyinput = new JTextField(15);
        dutyinput = new JTextField(15);
        salaryinput = new JTextField(15);
        JTextField[] textFields = { sexyinput, addressinput, homeaddressinput, cityinput, companyinput, dutyinput,
                salaryinput };

        Dimension commonSize = new Dimension(150, nameinput.getPreferredSize().height);

        // 设置所有 JTextField 和 JComboBox 的宽度一致
        for (JTextField textField : textFields) {
            textField.setPreferredSize(commonSize);
        }
        nameinput.setPreferredSize(commonSize);

        // 添加组件到面板
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // 设置间距

        // 添加标题
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 4; // 跨 4 列
        gbc.anchor = GridBagConstraints.CENTER; // 居中对齐
        gbc.insets = new Insets(20, 5, 15, 5); // 上方间距增加,向上移动
        add(titleLabel, gbc);

        // 添加左侧标签和控件
        for (int i = 0; i < labels.length; i++) {
            gbc.gridwidth = 1; // 单独占 1 列
            gbc.insets = new Insets(5, 5, 5, 5); // 恢复默认间距

            // 添加 JLabel (右对齐)
            gbc.gridx = (i < 4) ? 0 : 2; // 左列或右列
            gbc.gridy = (i < 4) ? i + 1 : i - 3;
            gbc.anchor = GridBagConstraints.EAST; // 右对齐
            add(labels[i], gbc);

            // 添加输入控件 (左对齐)
            gbc.gridx = (i < 4) ? 1 : 3; // 左列或右列对应的控件
            gbc.anchor = GridBagConstraints.WEST; // 左对齐
            if (i == 0) { // 第一行为 JComboBox (姓名)
                add(nameinput, gbc);
            } else {
                add(textFields[i - 1], gbc);
            }
        }

        // 从数据库加载数据并填充到控件
        Vector<ClassMate> classMateData = classMateStore.getClassMate(conn, SQL_QUERY);
        for (ClassMate mate : classMateData) {
            nameinput.addItem(mate.getName()); // 填充姓名到 JComboBox
        }

        // 添加 JComboBox 选择事件监听器
        nameinput.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedName = (String) nameinput.getSelectedItem();
                if (selectedName != null) {
                    for (ClassMate mate : classMateData) {
                        if (mate.getName().equals(selectedName)) {
                            sexyinput.setText(mate.getSex());
                            addressinput.setText(mate.getAddress());
                            homeaddressinput.setText(mate.getHomeaddress());
                            cityinput.setText(mate.getCity());
                            companyinput.setText(mate.getCompany());
                            dutyinput.setText(mate.getDuty());
                            salaryinput.setText(String.valueOf(mate.getSalary()));
                            break;
                        }
                    }
                }
            }
        });
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("同学基本信息");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new ClassMateInfo());
        frame.setVisible(true);
    }
}
同学联系面板:ClassMateCommunication.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
public class ClassMateCommunication extends JPanel {

    private static final long serialVersionUID = 4L;
    private static final String SQL_QUERY = "SELECT * FROM classmate";
    private ClassMateStore classMateStore = new ClassMateStore();
    private Connection conn = classMateStore.getConnection();
    private JComboBox<String> comboBox;
    private JTextField homephoneField;
    private JTextField contactField;

    public ClassMateCommunication() {
        this.setLayout(new java.awt.GridBagLayout());

        // 创建组件
        JLabel nameLabel = new JLabel("姓名:");
        comboBox = new JComboBox<>();
        JLabel homephoneLabel = new JLabel("家庭电话号码:");
        homephoneField = new JTextField(15);
        JLabel contactLabel = new JLabel("个人电话号码:");
        contactField = new JTextField(15);
        JButton closeButton = new JButton("关闭此窗口");

        // 加载数据
        Vector<ClassMate> classMateData = loadClassMateData();

        // 添加组件
        addComponent(nameLabel, 0, 0, 1, GridBagConstraints.EAST);
        addComponent(comboBox, 1, 0, 2, GridBagConstraints.WEST);
        addComponent(homephoneLabel, 0, 1, 1, GridBagConstraints.EAST);
        addComponent(homephoneField, 1, 1, 2, GridBagConstraints.WEST);
        addComponent(contactLabel, 0, 2, 1, GridBagConstraints.EAST);
        addComponent(contactField, 1, 2, 2, GridBagConstraints.WEST);
        addComponent(closeButton, 1, 3, 1, GridBagConstraints.CENTER);

        // 按钮事件
        closeButton.addActionListener(e -> {
            this.removeAll();
            this.revalidate();
            this.repaint();
        });

        // 下拉框事件监听
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedName = (String) comboBox.getSelectedItem();
                if (selectedName != null) {
                    for (ClassMate mate : classMateData) {
                        if (mate.getName().equals(selectedName)) {
                            homephoneField.setText(mate.getHomephone());
                            contactField.setText(mate.getContact());
                            break;
                        }
                    }
                }
            }
        });
    }

    /**
     * 添加组件的辅助方法,简化 GridBagConstraints 的设置
     *
     * @param component 组件
     * @param gridx     横坐标
     * @param gridy     纵坐标
     * @param gridwidth 占用的列数
     * @param anchor    对齐方式
     */
    private void addComponent(Component component, int gridx, int gridy, int gridwidth, int anchor) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = gridx;
        gbc.gridy = gridy;
        gbc.gridwidth = gridwidth;
        gbc.insets = new Insets(5, 5, 5, 5); // 设置间距
        gbc.anchor = anchor;
        gbc.fill = GridBagConstraints.HORIZONTAL; // 横向填充
        add(component, gbc);
    }

    /**
     * 加载同学数据到下拉框
     */
    private Vector<ClassMate> loadClassMateData() {
        Vector<ClassMate> classMateData = new Vector<>();
        try {
            classMateData = classMateStore.getClassMate(conn, SQL_QUERY);
            for (ClassMate mate : classMateData) {
                comboBox.addItem(mate.getName());
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "加载数据失败:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
        return classMateData;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("AdapterClass");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new ClassMateCommunication());
        frame.setVisible(true);
    }

}
同学查询面板:ClassMateFind.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
public class ClassMateFind {
    static JPanel panel;
    private JTextField nameInput, addressInput, homeAddressInput, sexyInput, cityInput, companyInput, dutyInput,
            salaryInput, searchTextField;
    private JLabel titleLabel;

    public ClassMateFind() {
        panel = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        panel.setLayout(gridbag);

        // Title label
        titleLabel = new JLabel("同学查询结果信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20)); // Font settings
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

        // Labels for student information
        JLabel[] labels = {
                new JLabel("姓名"), new JLabel("性别"), new JLabel("居住地址"),
                new JLabel("家庭地址"), new JLabel("所在城市"),
                new JLabel("所在公司"), new JLabel("职务"), new JLabel("薪水")
        };

        // Creating JTextFields for input
        nameInput = new JTextField(15);
        addressInput = new JTextField(15);
        homeAddressInput = new JTextField(15);
        sexyInput = new JTextField(15);
        cityInput = new JTextField(15);
        companyInput = new JTextField(15);
        dutyInput = new JTextField(15);
        salaryInput = new JTextField(15);
        JTextField[] textFields = { sexyInput, addressInput, homeAddressInput, cityInput, companyInput, dutyInput,
                salaryInput };

        // Set all JTextFields with the same size
        Dimension commonSize = new Dimension(150, nameInput.getPreferredSize().height);
        for (JTextField textField : textFields) {
            textField.setPreferredSize(commonSize);
        }

        // Adding components to the panel using GridBagLayout
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // Padding for components

        // Title label
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 4; // Title spans across 4 columns
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(20, 5, 15, 5); // Top padding
        addComponent(titleLabel, gbc);

        // Labels and input fields
        for (int i = 0; i < labels.length; i++) {
            gbc.gridwidth = 1;
            gbc.insets = new Insets(5, 5, 5, 5); // Default padding

            // Add labels (aligned to the right)
            gbc.gridx = (i < 4) ? 0 : 2; // Left or right column
            gbc.gridy = (i < 4) ? i + 1 : i - 3;
            gbc.anchor = GridBagConstraints.EAST;
            addComponent(labels[i], gbc);

            // Add input fields (aligned to the left)
            gbc.gridx = (i < 4) ? 1 : 3; // Corresponding input fields
            gbc.anchor = GridBagConstraints.WEST;
            if (i == 0) { // First field is the name input
                addComponent(nameInput, gbc);
            } else {
                addComponent(textFields[i - 1], gbc);
            }
        }

        JLabel titleLabel1 = new JLabel("查询系统");
        titleLabel1.setFont(new Font("微软雅黑", Font.BOLD, 20)); // Font settings
        titleLabel1.setHorizontalAlignment(SwingConstants.CENTER);
        gbc.gridx = 0;
        gbc.gridy = 9; // Place it below the existing input fields
        gbc.gridwidth = 4;
        gbc.anchor = GridBagConstraints.CENTER;
        addComponent(titleLabel1, gbc);

        // Adding the new "按姓名查询" label and text field for searching
        JLabel searchLabel = new JLabel("按姓名查询:");
        searchTextField = new JTextField(15);

        gbc.gridx = 0;
        gbc.gridy = 10; // Place it below the existing input fields
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(searchLabel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 10;
        gbc.gridwidth = 2; // Spanning 2 columns for the search field
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(searchTextField, gbc);

        // Adding the search button next to the search text field
        JButton searchButton = new JButton("查询");
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                queryClassmateInfo(searchTextField.getText());
            }
        });

        gbc.gridx = 3;
        gbc.gridy = 10;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(searchButton, gbc);

    }

    // Method to add components to the panel
    private void addComponent(Component c, GridBagConstraints constraints) {
        panel.add(c, constraints);
    }

    // Simulate querying the classmate info and updating text fields
    private void queryClassmateInfo(String name) {
        // Creating an instance of ClassMateStore to interact with the database
        ClassMateStore store = new ClassMateStore();
        Connection conn = store.getConnection();

        if (conn == null) {
            JOptionPane.showMessageDialog(panel, "无法连接到数据库", "数据库连接错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // SQL query to fetch the classmate data based on the name input
        String query = "SELECT * FROM classmate WHERE name = ?";

        try (PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, name); // Set the input name as parameter
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                // Populate the JTextFields with the data from the database
                nameInput.setText(rs.getString("name"));
                addressInput.setText(rs.getString("address"));
                homeAddressInput.setText(rs.getString("homeaddress"));
                sexyInput.setText(rs.getString("sex"));
                cityInput.setText(rs.getString("city"));
                companyInput.setText(rs.getString("company"));
                dutyInput.setText(rs.getString("duty"));
                salaryInput.setText(rs.getString("salary"));
            } else {
                // If no result found
                JOptionPane.showMessageDialog(panel, "未找到该同学信息", "查询结果", JOptionPane.INFORMATION_MESSAGE);
                resetFields();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(panel, "查询失败: " + e.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void resetFields() {
        addressInput.setText("");
        homeAddressInput.setText("");
        sexyInput.setText("");
        cityInput.setText("");
        companyInput.setText("");
        dutyInput.setText("");
        salaryInput.setText("");
        nameInput.setText(""); // Clear the name field
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("同学查询系统");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 500); // Increased size for extra components
        frame.setLocationRelativeTo(null);

        // Initialize and add ClassMateFind panel
        ClassMateFind classMateFind = new ClassMateFind();
        frame.add(classMateFind.panel);

        frame.setVisible(true);
    }
}
同学持久化类:ClassMateStore.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class ClassMateStore {
    public Vector<ClassMate> getClassMate(Connection conn, String sql) {
        Vector<ClassMate> v = new Vector<>();
        try (Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                ClassMate classMate = new ClassMate(rs.getString("name"));
                classMate.setSex(rs.getString("sex"));
                classMate.setAddress(rs.getString("address"));
                classMate.setHomeaddress(rs.getString("homeaddress"));
                classMate.setCity(rs.getString("city"));
                classMate.setCompany(rs.getString("company"));
                classMate.setDuty(rs.getString("duty"));
                classMate.setSalary(rs.getString("salary"));
                classMate.setContact(rs.getString("contact"));
                classMate.setHomephone(rs.getString("homephone"));
                v.add(classMate);
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return v;
    }

    public ClassMate getObject(Connection conn, String name) {
        ClassMate classMate = null;
        try (Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("select * from classmate where name='" + name + "'")) {
            while (rs.next()) {
                classMate = new ClassMate(rs.getString("name"));
                classMate.setSex(rs.getString("sex"));
                classMate.setAddress(rs.getString("address"));
                classMate.setHomeaddress(rs.getString("homeaddress"));
                classMate.setCity(rs.getString("city"));
                classMate.setCompany(rs.getString("company"));
                classMate.setDuty(rs.getString("duty"));
                classMate.setSalary(rs.getString("salary"));
                classMate.setContact(rs.getString("contact"));
                classMate.setHomephone(rs.getString("homephone"));
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return classMate;
    }

    public Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/combook?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
        String user = "root";
        String password = "root";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // 更新驱动类名
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
添加同学面板:AddClassMate.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
public class AddClassMate extends JPanel {

    private static final long serialVersionUID = 1L;
    private JTextField[] textFields;
    private DefaultComboBoxModel<String> model;

    public AddClassMate() {
        this.setLayout(new java.awt.GridBagLayout());

        model = new DefaultComboBoxModel<>();

        // 创建标题
        JLabel titleLabel = new JLabel("添加同学信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

        // 定义标签和输入框
        String[] labelNames = {
                "姓名", "性别", "居住地址", "家庭地址", "移动电话",
                "所在城市", "所在公司", "职务", "薪水", "家庭电话"
        };

        JLabel[] labels = new JLabel[labelNames.length];
        textFields = new JTextField[labelNames.length];

        for (int i = 0; i < labelNames.length; i++) {
            labels[i] = new JLabel(labelNames[i] + ":");
            textFields[i] = new JTextField(15);
        }

        JButton addButton = new JButton("添加同学信息");

        // 布局组件
        GridBagConstraints gbc = new GridBagConstraints();

        // 添加标题
        gbc.gridx = 0;
        gbc.gridy = 0; // 位于第 0 行
        gbc.gridwidth = 5; // 跨越 4 列,确保它占据整个窗口宽度
        gbc.anchor = GridBagConstraints.CENTER; // 居中对齐
        gbc.fill = GridBagConstraints.HORIZONTAL; // 水平方向填充
        gbc.insets = new Insets(10, 0, 25, 0); // 上下间距,增强美观
        add(titleLabel, gbc);

        for (int i = 0; i < labels.length; i++) {
            gbc.insets = new Insets(5, 5, 5, 5);
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridwidth = 1; // 单独占 1 列
            // 添加 JLabel (右对齐)
            gbc.gridx = (i < 5) ? 0 : 2; // 左列或右列
            gbc.gridy = (i < 5) ? i + 1 : i - 4;
            gbc.anchor = GridBagConstraints.EAST; // 右对齐
            add(labels[i], gbc);

            // 添加输入控件 (左对齐)
            gbc.gridx = (i < 5) ? 1 : 4; // 左列或右列对应的控件
            gbc.anchor = GridBagConstraints.WEST; // 左对齐
            add(textFields[i], gbc);
        }

        // 添加按钮
        gbc.gridx = 0;
        gbc.gridy = labelNames.length + 1;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        add(addButton, gbc);

        // 添加按钮事件监听
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (validateInputs()) {
                    addClassMateToDatabase();
                }
            }
        });
    }

    /**
     * 将同学信息保存到数据库
     */
    private void addClassMateToDatabase() {
        String[] values = getTextFieldValues();
        ClassMateService service = new ClassMateService();
        if (service.addClassMate(values)) {
            updateClassMateInfo(values);
            JOptionPane.showMessageDialog(this, "添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            // ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); // 关闭当前窗口
        } else {
            JOptionPane.showMessageDialog(this, "添加失败,请重试。", "失败", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String[] getTextFieldValues() {
        String[] values = new String[textFields.length];
        for (int i = 0; i < textFields.length; i++) {
            values[i] = textFields[i].getText().trim();
        }
        String temp = values[4];
        values[4] = values[5];
        values[5] = values[6];
        values[6] = values[7];
        values[7] = values[8];
        values[8] = temp;
        return values;
    }

    private void updateClassMateInfo(String[] values) {

        // 确保 ClassMateInfo 中的组件已初始化
        if (ClassMateInfo.nameinput == null) {
            ClassMateInfo.nameinput = new JComboBox<>(model);
        }
        if (ClassMateInfo.addressinput == null) {
            ClassMateInfo.addressinput = new JTextField();
        }
        if (ClassMateInfo.sexyinput == null) {
            ClassMateInfo.sexyinput = new JTextField();
        }
        if (ClassMateInfo.homeaddressinput == null) {
            ClassMateInfo.homeaddressinput = new JTextField();
        }
        if (ClassMateInfo.companyinput == null) {
            ClassMateInfo.companyinput = new JTextField();
        }
        if (ClassMateInfo.dutyinput == null) {
            ClassMateInfo.dutyinput = new JTextField();
        }
        if (ClassMateInfo.salaryinput == null) {
            ClassMateInfo.salaryinput = new JTextField();
        }
        if (ClassMateInfo.cityinput == null) {
            ClassMateInfo.cityinput = new JTextField();
        }

        ClassMate classmate = new ClassMate(values[0]);
        classmate.setName(values[0]);
        classmate.setSex(values[1]);
        classmate.setAddress(values[2]);
        classmate.setHomeaddress(values[3]);
        classmate.setCity(values[4]);
        classmate.setCompany(values[5]);
        classmate.setDuty(values[6]);
        classmate.setSalary(values[7]);
        classmate.setContact(values[8]);
        classmate.setHomephone(values[9]);

        Vector<ClassMate> classmateVector = new Vector<>();
        classmateVector.add(classmate);

        ClassMateInfo.nameinput.addItem(values[0]);
        ClassMateInfo.nameinput.setSelectedItem(values[0]);
        ClassMateInfo.addressinput.setText(values[2]);
        ClassMateInfo.sexyinput.setText(values[1]);
        ClassMateInfo.homeaddressinput.setText(values[3]);
        ClassMateInfo.companyinput.setText(values[5]);
        ClassMateInfo.dutyinput.setText(values[6]);
        ClassMateInfo.salaryinput.setText(values[7]);
        ClassMateInfo.cityinput.setText(values[4]);

    }

    private boolean validateInputs() {
        for (JTextField textField : textFields) {
            if (textField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写所有必填项!", "输入错误", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("添加同学信息");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new AddClassMate());
        frame.setVisible(true);
    }
}

class ClassMateService {
    private static final String INSERT_SQL = "INSERT INTO classmate (name, sex, address, homeAddress, city, company,  duty, salary, contact, homePhone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    public boolean addClassMate(String... values) {
        try (Connection conn = new ClassMateStore().getConnection();
                PreparedStatement stmt = conn.prepareStatement(INSERT_SQL)) {

            for (int i = 0; i < values.length; i++) {
                stmt.setString(i + 1, values[i]);
            }

            return stmt.executeUpdate() > 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
删除同学类:DelClassMate.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class DelClassMate {

    public DelClassMate() {
        String name = ClassMateInfo.nameinput.getSelectedItem().toString();
        ClassMateStore classMateStore = new ClassMateStore();
        try (Connection conn = classMateStore.getConnection();
                PreparedStatement stmt = conn.prepareStatement("delete from classmate where name = ?")) {
            stmt.setString(1, name);
            int rowsAffected = stmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "删除失败,请重试。", "失败", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库操作失败,请重试。", "失败", JOptionPane.ERROR_MESSAGE);
        } finally {
            ClassMateInfo.nameinput.removeItem(name);
        }
    }
}
修改同学类:UpdateClassMate.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class UpdateClassMate {
    ClassMateStore classMateStore = new ClassMateStore();
    Connection conn = classMateStore.getConnection();

    public UpdateClassMate() {
        try (PreparedStatement pstmt = conn.prepareStatement(
                "UPDATE classmate SET sex = ?, address = ?, homeaddress = ?, city = ?, company = ?, duty = ?, salary = ? WHERE name = ?")) {

            String sex = ClassMateInfo.sexyinput.getText();
            String name = ClassMateInfo.nameinput.getSelectedItem().toString();
            String address = ClassMateInfo.addressinput.getText();
            String homeaddress = ClassMateInfo.homeaddressinput.getText();
            String city = ClassMateInfo.cityinput.getText();
            String company = ClassMateInfo.companyinput.getText();
            String duty = ClassMateInfo.dutyinput.getText();
            String salary = ClassMateInfo.salaryinput.getText();

            pstmt.setString(1, sex);
            pstmt.setString(2, address);
            pstmt.setString(3, homeaddress);
            pstmt.setString(4, city);
            pstmt.setString(5, company);
            pstmt.setString(6, duty);
            pstmt.setString(7, salary);
            pstmt.setString(8, name);

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "修改成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "未找到匹配的记录!", "失败", JOptionPane.ERROR_MESSAGE);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "发生错误:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
2. 同事相关类
同事类:Company.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
public class Company {
    private String name;
    private String code;
    private String birthday;
    private String sex;
    private String address;
    private String duty;
    private String salary;
    private String tel;
    private String motel;
    private String department;

    public Company(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getDuty() {
        return duty;
    }

    public void setDuty(String duty) {
        this.duty = duty;
    }

    public String getSalary() {
        return salary;
    }

    public void setSalary(String salary) {
        this.salary = salary;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getMotel() {
        return motel;
    }

    public void setMotel(String motel) {
        this.motel = motel;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Company [name=" + name + ", code=" + code + ", birthday=" + birthday + ", sex=" + sex + ", address="
                + address + ", duty=" + duty + ", salary=" + salary + ", tel=" + tel + ", motel=" + motel
                + ", department=" + department + "]";
    }

}
同事信息面板:CompanyInfo.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
public class CompanyInfo extends JPanel {
    private static final long serialVersionUID = 2L;
    private static final String SQL_QUERY = "SELECT * FROM company";
    private CompanyStore companyStore = new CompanyStore();
    private Connection conn = companyStore.getConnection();

    public static JComboBox<String> nameinput;
    public static JTextField codeinput;
    public static JTextField sexinput;
    public static JTextField departmentinput;
    public static JTextField addressinput;
    public static JTextField birthdayinput;
    public static JTextField dutyinput;
    public static JTextField salaryinput;
    public DefaultComboBoxModel<String> model;

    public CompanyInfo() {
        this.setLayout(new java.awt.GridBagLayout());

        // 创建 DefaultComboBoxModel
        DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();

        // 创建标题
        JLabel titleLabel = new JLabel("同事基本信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20)); // 设置字体和大小
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

        JLabel[] labels = {
                new JLabel("姓名"), new JLabel("工号"), new JLabel("部门"),
                new JLabel("性别"), new JLabel("家庭地址"),
                new JLabel("出生年月"), new JLabel("职务"), new JLabel("薪水")
        };

        // 创建 JTextField 和 JComboBox
        nameinput = new JComboBox<>(model);
        codeinput = new JTextField(15);
        sexinput = new JTextField(15);
        departmentinput = new JTextField(15);
        addressinput = new JTextField(15);
        birthdayinput = new JTextField(15);
        dutyinput = new JTextField(15);
        salaryinput = new JTextField(15);

        JTextField[] textFields = { codeinput, departmentinput, sexinput, addressinput, birthdayinput,
                dutyinput, salaryinput };

        Dimension commonSize = new Dimension(150, nameinput.getPreferredSize().height);

        // 设置所有 JTextField 和 JComboBox 的宽度一致
        for (JTextField textField : textFields) {
            textField.setPreferredSize(commonSize);
        }
        nameinput.setPreferredSize(commonSize);

        // 设置所有 JTextField 和 JComboBox 的宽度一致
        for (JTextField textField : textFields) {
            textField.setPreferredSize(commonSize);
        }
        nameinput.setPreferredSize(commonSize);

        // 添加组件到面板
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // 设置间距

        // 添加标题
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 4; // 跨 4 列
        gbc.anchor = GridBagConstraints.CENTER; // 居中对齐
        gbc.insets = new Insets(20, 5, 15, 5); // 上方间距增加,向上移动
        add(titleLabel, gbc);

        // 添加左侧标签和控件
        for (int i = 0; i < labels.length; i++) {
            gbc.gridwidth = 1; // 单独占 1 列
            gbc.insets = new Insets(5, 5, 5, 5); // 恢复默认间距

            // 添加 JLabel (右对齐)
            gbc.gridx = (i < 4) ? 0 : 2; // 左列或右列
            gbc.gridy = (i < 4) ? i + 1 : i - 3;
            gbc.anchor = GridBagConstraints.EAST; // 右对齐
            add(labels[i], gbc);

            // 添加输入控件 (左对齐)
            gbc.gridx = (i < 4) ? 1 : 3; // 左列或右列对应的控件
            gbc.anchor = GridBagConstraints.WEST; // 左对齐
            if (i == 0) { // 第一行为 JComboBox (姓名)
                add(nameinput, gbc);
            } else {
                add(textFields[i - 1], gbc);
            }
        }

        // 从数据库加载数据并填充到控件
        Vector<Company> companyMateData = companyStore.getCompany(conn, SQL_QUERY);
        for (Company mate : companyMateData) {
            nameinput.addItem(mate.getName()); // 填充姓名到 JComboBox
        }

        // 添加 JComboBox 选择事件监听器
        nameinput.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedName = (String) nameinput.getSelectedItem();
                if (selectedName != null) {
                    for (Company mate : companyMateData) {
                        if (mate.getName().equals(selectedName)) {
                            codeinput.setText(mate.getCode());
                            departmentinput.setText(mate.getDepartment());
                            sexinput.setText(mate.getSex());
                            addressinput.setText(mate.getAddress());
                            birthdayinput.setText(mate.getBirthday());
                            dutyinput.setText(mate.getDuty());
                            salaryinput.setText(String.valueOf(mate.getSalary()));
                            break;
                        }
                    }
                }
            }
        });
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("添加同事信息");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new CompanyInfo());
        frame.setVisible(true);
    }
}
同事联系面板:CompanyCommunication.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
public class CompanyCommunication extends JPanel {

    private static final long serialVersionUID = 4L;
    private static final String SQL_QUERY = "SELECT * FROM company";
    private CompanyStore companyMateStore = new CompanyStore();
    private Connection conn = companyMateStore.getConnection();
    private JComboBox<String> comboBox;
    private JTextField homephoneField;
    private JTextField contactField;

    public CompanyCommunication() {
        this.setLayout(new java.awt.GridBagLayout());

        // 创建组件
        JLabel nameLabel = new JLabel("姓名:");
        comboBox = new JComboBox<>();
        JLabel homephoneLabel = new JLabel("家庭电话号码:");
        homephoneField = new JTextField(15);
        JLabel contactLabel = new JLabel("个人电话号码:");
        contactField = new JTextField(15);
        JButton closeButton = new JButton("关闭此窗口");

        // 加载数据
        Vector<Company> companyMateData = loadClassMateData();

        // 添加组件
        addComponent(nameLabel, 0, 0, 1, GridBagConstraints.EAST);
        addComponent(comboBox, 1, 0, 2, GridBagConstraints.WEST);
        addComponent(homephoneLabel, 0, 1, 1, GridBagConstraints.EAST);
        addComponent(homephoneField, 1, 1, 2, GridBagConstraints.WEST);
        addComponent(contactLabel, 0, 2, 1, GridBagConstraints.EAST);
        addComponent(contactField, 1, 2, 2, GridBagConstraints.WEST);
        addComponent(closeButton, 1, 3, 1, GridBagConstraints.CENTER);

        // 按钮事件
        closeButton.addActionListener(e -> {
            this.removeAll();
            this.revalidate();
            this.repaint();
        });

        // 下拉框事件监听
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedName = (String) comboBox.getSelectedItem();
                if (selectedName != null) {
                    for (Company mate : companyMateData) {
                        if (mate.getName().equals(selectedName)) {
                            homephoneField.setText(mate.getTel());
                            contactField.setText(mate.getMotel());
                            break;
                        }
                    }
                }
            }
        });
    }

    /**
     * 添加组件的辅助方法,简化 GridBagConstraints 的设置
     *
     * @param component 组件
     * @param gridx     横坐标
     * @param gridy     纵坐标
     * @param gridwidth 占用的列数
     * @param anchor    对齐方式
     */
    private void addComponent(Component component, int gridx, int gridy, int gridwidth, int anchor) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = gridx;
        gbc.gridy = gridy;
        gbc.gridwidth = gridwidth;
        gbc.insets = new Insets(5, 5, 5, 5); // 设置间距
        gbc.anchor = anchor;
        gbc.fill = GridBagConstraints.HORIZONTAL; // 横向填充
        add(component, gbc);
    }

    /**
     * 加载同事数据到下拉框
     */
    private Vector<Company> loadClassMateData() {
        Vector<Company> companyMateData = new Vector<>();
        try {
            companyMateData = companyMateStore.getCompany(conn, SQL_QUERY);
            for (Company mate : companyMateData) {
                comboBox.addItem(mate.getName());
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "加载数据失败:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
        return companyMateData;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("AdapterClass");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new CompanyCommunication());
        frame.setVisible(true);
    }
}
同事查询面板:CompanyFind.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
public class CompanyFind {
    static JPanel panel;
    private JTextField nameInput, codeInput, sexInput, departmentInput, birthdayInput, addressInput, dutyInput,
            salaryInput, searchTextField;
    private JLabel titleLabel;

    public CompanyFind() {
        panel = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        panel.setLayout(gridbag);

        // Title label
        titleLabel = new JLabel("同事查询结果信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20)); // Font settings
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

        // Labels for student information
        JLabel[] labels = {
                new JLabel("姓名"), new JLabel("工号"), new JLabel("性别"),
                new JLabel("部门"), new JLabel("出生年月"),
                new JLabel("家庭地址"), new JLabel("职位"), new JLabel("薪水")
        };

        nameInput = new JTextField(15);
        codeInput = new JTextField(15);
        sexInput = new JTextField(15);
        departmentInput = new JTextField(15);
        birthdayInput = new JTextField(15);
        addressInput = new JTextField(15);
        dutyInput = new JTextField(15);
        salaryInput = new JTextField(15);

        JTextField[] textFields = { codeInput, sexInput, departmentInput, birthdayInput, addressInput,
                dutyInput, salaryInput };

        // Set all JTextFields with the same size
        Dimension commonSize = new Dimension(150, nameInput.getPreferredSize().height);
        for (JTextField textField : textFields) {
            textField.setPreferredSize(commonSize);
        }

        // Adding components to the panel using GridBagLayout
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // Padding for components

        // Title label
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 4; // Title spans across 4 columns
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(20, 5, 15, 5); // Top padding
        addComponent(titleLabel, gbc);

        // Labels and input fields
        for (int i = 0; i < labels.length; i++) {
            gbc.gridwidth = 1;
            gbc.insets = new Insets(5, 5, 5, 5); // Default padding

            // Add labels (aligned to the right)
            gbc.gridx = (i < 4) ? 0 : 2; // Left or right column
            gbc.gridy = (i < 4) ? i + 1 : i - 3;
            gbc.anchor = GridBagConstraints.EAST;
            addComponent(labels[i], gbc);

            // Add input fields (aligned to the left)
            gbc.gridx = (i < 4) ? 1 : 3; // Corresponding input fields
            gbc.anchor = GridBagConstraints.WEST;
            if (i == 0) { // First field is the name input
                addComponent(nameInput, gbc);
            } else {
                addComponent(textFields[i - 1], gbc);
            }
        }

        JLabel titleLabel1 = new JLabel("查询系统");
        titleLabel1.setFont(new Font("微软雅黑", Font.BOLD, 20)); // Font settings
        titleLabel1.setHorizontalAlignment(SwingConstants.CENTER);
        gbc.gridx = 0;
        gbc.gridy = 9; // Place it below the existing input fields
        gbc.gridwidth = 4;
        gbc.anchor = GridBagConstraints.CENTER;
        addComponent(titleLabel1, gbc);

        // Adding the new "按姓名查询" label and text field for searching
        JLabel searchLabel = new JLabel("按姓名查询:");
        searchTextField = new JTextField(15);

        gbc.gridx = 0;
        gbc.gridy = 10; // Place it below the existing input fields
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(searchLabel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 10;
        gbc.gridwidth = 2; // Spanning 2 columns for the search field
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(searchTextField, gbc);

        // Adding the search button next to the search text field
        JButton searchButton = new JButton("查询");
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                queryClassmateInfo(searchTextField.getText());
            }
        });

        gbc.gridx = 3;
        gbc.gridy = 10;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(searchButton, gbc);
    }

    // Method to add components to the panel
    private void addComponent(Component c, GridBagConstraints constraints) {
        panel.add(c, constraints);
    }

    private void queryClassmateInfo(String name) {
        // Creating an instance of ClassMateStore to interact with the database
        CompanyStore store = new CompanyStore();
        Connection conn = store.getConnection();

        if (conn == null) {
            JOptionPane.showMessageDialog(panel, "无法连接到数据库", "数据库连接错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // SQL query to fetch the classmate data based on the name input
        String query = "SELECT * FROM company WHERE name = ?";

        try (PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, name); // Set the input name as parameter
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                // Populate the JTextFields with the data from the database
                nameInput.setText(rs.getString("name"));
                codeInput.setText(rs.getString("code"));
                sexInput.setText(rs.getString("sex"));
                departmentInput.setText(rs.getString("department"));
                birthdayInput.setText(rs.getString("birthday"));
                addressInput.setText(rs.getString("address"));
                dutyInput.setText(rs.getString("duty"));
                salaryInput.setText(rs.getString("salary"));
            } else {
                // If no result found
                JOptionPane.showMessageDialog(panel, "未找到该同学信息", "查询结果", JOptionPane.INFORMATION_MESSAGE);
                resetFields();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(panel, "查询失败: " + e.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void resetFields() {
        nameInput.setText("");
        codeInput.setText("");
        sexInput.setText("");
        departmentInput.setText("");
        birthdayInput.setText("");
        addressInput.setText("");
        dutyInput.setText("");
        salaryInput.setText(""); // Clear the name field
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("同学查询系统");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 500); // Increased size for extra components
        frame.setLocationRelativeTo(null);

        // Initialize and add ClassMateFind panel
        CompanyFind companyFind = new CompanyFind();
        frame.add(companyFind.panel);

        frame.setVisible(true);
    }
}
同事持久化类:CompanyStore.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

    public Vector<Company> getCompany(Connection conn, String sql) {
        Vector<Company> v = new Vector<>();
        try (Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                Company company = new Company(rs.getString("name"));
                company.setCode(rs.getString("code"));
                company.setBirthday(rs.getString("birthday"));
                company.setSex(rs.getString("sex"));
                company.setAddress(rs.getString("address"));
                company.setDuty(rs.getString("duty"));
                company.setSalary(rs.getString("salary"));
                company.setTel(rs.getString("tel"));
                company.setMotel(rs.getString("motel"));
                company.setDepartment(rs.getString("department"));
                v.add(company);
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return v;
    }

    public Company getObject(Connection conn, String name) {
        Company company = null;
        String sql = "select * from company where name='" + name + "'";
        try (Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                company = new Company(rs.getString("name"));
                company.setCode(rs.getString("code"));
                company.setBirthday(rs.getString("birthday"));
                company.setSex(rs.getString("sex"));
                company.setAddress(rs.getString("address"));
                company.setDuty(rs.getString("duty"));
                company.setSalary(rs.getString("salary"));
                company.setTel(rs.getString("tel"));
                company.setMotel(rs.getString("motel"));
                company.setDepartment(rs.getString("department"));

            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return company;
    }

    public Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/combook";
        String user = "root";
        String password = "root";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // 更新驱动类名
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
添加同事面板:AddCompany.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
public class AddCompany extends JPanel {

    private static final long serialVersionUID = 10L;
    private JTextField[] textFields;
    private DefaultComboBoxModel<String> model;

    public AddCompany() {
        this.setLayout(new java.awt.GridBagLayout());

        model = new DefaultComboBoxModel<String>();

        // 创建标题
        JLabel titleLabel = new JLabel("添加同事信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

        // 定义标签和输入框
        String[] labelNames = {
                "姓名", "工号", "部门", "性别", "公司电话",
                "家庭地址", "出生年月", "职位", "薪水", "移动电话"
        };

        JLabel[] labels = new JLabel[labelNames.length];
        textFields = new JTextField[labelNames.length];

        for (int i = 0; i < labelNames.length; i++) {
            labels[i] = new JLabel(labelNames[i] + ":");
            textFields[i] = new JTextField(15);
        }

        JButton addButton = new JButton("添加同事信息");

        // 布局组件
        GridBagConstraints gbc = new GridBagConstraints();

        // 添加标题
        gbc.gridx = 0;
        gbc.gridy = 0; // 位于第 0 行
        gbc.gridwidth = 5; // 跨越 4 列,确保它占据整个窗口宽度
        gbc.anchor = GridBagConstraints.CENTER; // 居中对齐
        gbc.fill = GridBagConstraints.HORIZONTAL; // 水平方向填充
        gbc.insets = new Insets(10, 0, 25, 0); // 上下间距,增强美观
        add(titleLabel, gbc);

        for (int i = 0; i < labels.length; i++) {
            gbc.insets = new Insets(5, 5, 5, 5);
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridwidth = 1; // 单独占 1 列
            // 添加 JLabel (右对齐)
            gbc.gridx = (i < 5) ? 0 : 2; // 左列或右列
            gbc.gridy = (i < 5) ? i + 1 : i - 4;
            gbc.anchor = GridBagConstraints.EAST; // 右对齐
            add(labels[i], gbc);

            // 添加输入控件 (左对齐)
            gbc.gridx = (i < 5) ? 1 : 4; // 左列或右列对应的控件
            gbc.anchor = GridBagConstraints.WEST; // 左对齐
            add(textFields[i], gbc);

        }

        // 添加按钮
        gbc.gridx = 0;
        gbc.gridy = labelNames.length + 1;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        add(addButton, gbc);

        // 添加按钮事件监听
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (validateInputs()) {
                    addCompanyToDatabase();
                }
            }
        });
    }

    /**
     * 将同学信息保存到数据库
     */
    private void addCompanyToDatabase() {

        String[] values = getTextFieldValues();
        CompanyService service = new CompanyService();

        if (service.addCompany(values)) {
            updateCompanyInfo(values);
            JOptionPane.showMessageDialog(this, "添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            // ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose();
        } else {
            JOptionPane.showMessageDialog(this, "添加失败,请重试。", "失败", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateCompanyInfo(String[] values) {

        // 确保 CompanyInfo 中的组件已初始化
        if (CompanyInfo.nameinput == null) {
            CompanyInfo.nameinput = new JComboBox<>(model);
        }
        if (CompanyInfo.codeinput == null) {
            CompanyInfo.codeinput = new JTextField();
        }
        if (CompanyInfo.sexinput == null) {
            CompanyInfo.sexinput = new JTextField();
        }
        if (CompanyInfo.departmentinput == null) {
            CompanyInfo.departmentinput = new JTextField();
        }
        if (CompanyInfo.addressinput == null) {
            CompanyInfo.addressinput = new JTextField();
        }
        if (CompanyInfo.birthdayinput == null) {
            CompanyInfo.birthdayinput = new JTextField();
        }
        if (CompanyInfo.dutyinput == null) {
            CompanyInfo.dutyinput = new JTextField();
        }
        if (CompanyInfo.salaryinput == null) {
            CompanyInfo.salaryinput = new JTextField();
        }

        Company company = new Company(values[0]);
        company.setName(values[0]);
        company.setCode(values[1]);
        company.setDepartment(values[2]);
        company.setSex(values[3]);
        company.setTel(values[4]);
        company.setAddress(values[5]);
        company.setBirthday(values[6]);
        company.setDuty(values[7]);
        company.setSalary(values[8]);
        company.setMotel(values[9]);

        Vector<Company> companyVector = new Vector<>();
        companyVector.add(company);

        CompanyInfo.nameinput.addItem(values[0]);
        CompanyInfo.nameinput.setSelectedItem(values[0]);
        CompanyInfo.codeinput.setText(values[1]);
        CompanyInfo.departmentinput.setText(values[2]);
        CompanyInfo.sexinput.setText(values[3]);
        CompanyInfo.birthdayinput.setText(values[6]);
        CompanyInfo.dutyinput.setText(values[7]);
        CompanyInfo.salaryinput.setText(values[8]);
    }

    private String[] getTextFieldValues() {
        String[] values = new String[textFields.length];
        for (int i = 0; i < textFields.length; i++) {
            values[i] = textFields[i].getText().trim();
        }
        return values;
    }

    private boolean validateInputs() {
        for (JTextField textField : textFields) {
            if (textField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写所有必填项!", "输入错误", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("添加同事信息");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new AddCompany());
        frame.setVisible(true);
    }

}

class CompanyService {
    private static final String INSERT_SQL = "INSERT INTO company (name, code, department, sex, tel, address, birthday, duty, salary, motel) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    public boolean addCompany(String... values) {
        try (Connection conn = new CompanyStore().getConnection();
                PreparedStatement stmt = conn.prepareStatement(INSERT_SQL)) {

            for (int i = 0; i < values.length; i++) {
                stmt.setString(i + 1, values[i]);
            }

            return stmt.executeUpdate() > 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
删除同事类:DelCompany.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class DelCompany {

    public DelCompany() {
        String name = CompanyInfo.nameinput.getSelectedItem().toString();
        CompanyStore companyStore = new CompanyStore();
        try (Connection conn = companyStore.getConnection();
                PreparedStatement stmt = conn.prepareStatement("delete from company where name = ?")) {
            stmt.setString(1, name);
            int rowsAffected = stmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "删除失败,请重试。", "失败", JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库操作失败,请重试。", "失败", JOptionPane.INFORMATION_MESSAGE);
        } finally {
            CompanyInfo.nameinput.removeItem(name);
        }
    }
}
修改同事类:UpdateCompany.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class UpdateCompany {
    CompanyStore companyStore = new CompanyStore();
    Connection conn = companyStore.getConnection();

    public UpdateCompany() {
        try (PreparedStatement pstmt = conn.prepareStatement(
                "UPDATE company SET sex = ?, address = ?, code = ?, department = ?, duty = ?, salary = ?, birthday = ? WHERE name = ?")) {

            String sex = CompanyInfo.sexinput.getText();
            String name = CompanyInfo.nameinput.getSelectedItem().toString();
            String address = CompanyInfo.addressinput.getText();
            String code = CompanyInfo.codeinput.getText();
            String department = CompanyInfo.departmentinput.getText();
            String duty = CompanyInfo.dutyinput.getText();
            String salary = CompanyInfo.salaryinput.getText();
            String birthday = CompanyInfo.birthdayinput.getText();

            pstmt.setString(1, sex);
            pstmt.setString(2, address);
            pstmt.setString(3, code);
            pstmt.setString(4, department);
            pstmt.setString(5, duty);
            pstmt.setString(6, salary);
            pstmt.setString(7, birthday);
            pstmt.setString(8, name);

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "修改成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "未找到匹配的记录!", "失败", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "发生错误:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
3. 朋友相关类
朋友类:Friend.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public class Friend {

    private String name;
    private String sex;
    private String birthday;
    private String address;
    private String company;
    private String duty;
    private String salary;
    private String tel;
    private String phone;

    Friend(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getDuty() {
        return duty;
    }

    public void setDuty(String duty) {
        this.duty = duty;
    }

    public String getSalary() {
        return salary;
    }

    public void setSalary(String salary) {
        this.salary = salary;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Friend [name=" + name + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address
                + ", company=" + company + ", duty=" + duty + ", salary=" + salary + ", tel=" + tel + ", phone=" + phone
                + "]";
    }

}
朋友信息面板:FriendInfo.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
public FriendInfo() {
        this.setLayout(new java.awt.GridBagLayout());

        // 创建 DefaultComboBoxModel
        DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();

        // 创建标题
        JLabel titleLabel = new JLabel("朋友基本信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20)); // 设置字体和大小
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

        JLabel[] labels = {
                new JLabel("姓名"), new JLabel("性别"), new JLabel("出生年月"),
                new JLabel("家庭地址"), new JLabel("所在公司"),
                new JLabel("职位"), new JLabel("薪水")
        };

        // 创建 JTextField 和 JComboBox
        nameinput = new JComboBox<>(model);
        sexyinput = new JTextField(15);
        birthdayinput = new JTextField(15);
        addressinput = new JTextField(15);
        companyinput = new JTextField(15);
        dutyinput = new JTextField(15);
        salaryinput = new JTextField(15);

        JTextField[] textFields = {
                sexyinput,
                birthdayinput,
                addressinput,
                companyinput,
                dutyinput,
                salaryinput };
        Dimension commonSize = new Dimension(150, nameinput.getPreferredSize().height);

        // 设置所有 JTextField 和 JComboBox 的宽度一致
        for (JTextField textField : textFields) {
            textField.setPreferredSize(commonSize);
        }
        nameinput.setPreferredSize(commonSize);

        // 添加组件到面板
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // 设置间距

        // 添加标题
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 4; // 跨 4 列
        gbc.anchor = GridBagConstraints.CENTER; // 居中对齐
        gbc.insets = new Insets(20, 5, 15, 5); // 上方间距增加,向上移动
        add(titleLabel, gbc);

        // 添加左侧标签和控件
        for (int i = 0; i < labels.length; i++) {
            gbc.gridwidth = 1; // 单独占 1 列
            gbc.insets = new Insets(5, 5, 5, 5); // 恢复默认间距

            // 添加 JLabel (右对齐)
            gbc.gridx = (i < 4) ? 0 : 2; // 左列或右列
            gbc.gridy = (i < 4) ? i + 1 : i - 3;
            gbc.anchor = GridBagConstraints.EAST; // 右对齐
            add(labels[i], gbc);

            // 添加输入控件 (左对齐)
            gbc.gridx = (i < 4) ? 1 : 3; // 左列或右列对应的控件
            gbc.anchor = GridBagConstraints.WEST; // 左对齐
            if (i == 0) { // 第一行为 JComboBox (姓名)
                add(nameinput, gbc);
            } else {
                add(textFields[i - 1], gbc);
            }
        }

        // 从数据库加载数据并填充到控件
        Vector<Friend> friendMateData = friendStore.getFriend(conn, SQL_QUERY);
        for (Friend mate : friendMateData) {
            nameinput.addItem(mate.getName()); // 填充姓名到 JComboBox
        }

        // 添加 JComboBox 选择事件监听器
        nameinput.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedName = (String) nameinput.getSelectedItem();
                if (selectedName != null) {
                    for (Friend mate : friendMateData) {
                        if (mate.getName().equals(selectedName)) {
                            sexyinput.setText(mate.getSex());
                            birthdayinput.setText(mate.getBirthday());
                            addressinput.setText(mate.getAddress());
                            companyinput.setText(mate.getCompany());
                            dutyinput.setText(mate.getDuty());
                            salaryinput.setText(String.valueOf(mate.getSalary()));
                            break;
                        }
                    }
                }
            }
        });
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("朋友信息");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new FriendInfo());
        frame.setVisible(true);
    }
}
朋友联系面板:FriendCommunication.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
public class FriendCommunication extends JPanel {

    private static final long serialVersionUID = 4L;
    private static final String SQL_QUERY = "SELECT * FROM friend";
    private FriendStore friendMateStore = new FriendStore();
    private Connection conn = friendMateStore.getConnection();
    private JComboBox<String> comboBox;
    private JTextField homephoneField;
    private JTextField contactField;

    public FriendCommunication() {
        this.setLayout(new java.awt.GridBagLayout());

        // 创建组件
        JLabel nameLabel = new JLabel("姓名:");
        comboBox = new JComboBox<>();
        JLabel homephoneLabel = new JLabel("家庭电话号码:");
        homephoneField = new JTextField(15);
        JLabel contactLabel = new JLabel("个人电话号码:");
        contactField = new JTextField(15);
        JButton closeButton = new JButton("关闭此窗口");

        // 加载数据
        Vector<Friend> friendMateData = loadClassMateData();

        // 添加组件
        addComponent(nameLabel, 0, 0, 1, GridBagConstraints.EAST);
        addComponent(comboBox, 1, 0, 2, GridBagConstraints.WEST);
        addComponent(homephoneLabel, 0, 1, 1, GridBagConstraints.EAST);
        addComponent(homephoneField, 1, 1, 2, GridBagConstraints.WEST);
        addComponent(contactLabel, 0, 2, 1, GridBagConstraints.EAST);
        addComponent(contactField, 1, 2, 2, GridBagConstraints.WEST);
        addComponent(closeButton, 1, 3, 1, GridBagConstraints.CENTER);

        // 按钮事件
        closeButton.addActionListener(e -> {
            this.removeAll();
            this.revalidate();
            this.repaint();
        });

        // 下拉框事件监听
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedName = (String) comboBox.getSelectedItem();
                if (selectedName != null) {
                    for (Friend mate : friendMateData) {
                        if (mate.getName().equals(selectedName)) {
                            homephoneField.setText(mate.getTel());
                            contactField.setText(mate.getPhone());
                            break;
                        }
                    }
                }
            }
        });
    }

    /**
     * 添加组件的辅助方法,简化 GridBagConstraints 的设置
     *
     * @param component 组件
     * @param gridx     横坐标
     * @param gridy     纵坐标
     * @param gridwidth 占用的列数
     * @param anchor    对齐方式
     */
    private void addComponent(Component component, int gridx, int gridy, int gridwidth, int anchor) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = gridx;
        gbc.gridy = gridy;
        gbc.gridwidth = gridwidth;
        gbc.insets = new Insets(5, 5, 5, 5); // 设置间距
        gbc.anchor = anchor;
        gbc.fill = GridBagConstraints.HORIZONTAL; // 横向填充
        add(component, gbc);
    }

    /**
     * 加载朋友数据到下拉框
     */
    private Vector<Friend> loadClassMateData() {
        Vector<Friend> friendMateData = new Vector<>();
        try {
            friendMateData = friendMateStore.getFriend(conn, SQL_QUERY);
            for (Friend mate : friendMateData) {
                comboBox.addItem(mate.getName());
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "加载数据失败:" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
        return friendMateData;
    }
}
朋友查询面板:FriendFind.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
public class FriendFind {
    static JPanel panel;
    private JTextField nameInput, sexInput, birthdayInput, addressInput, companyInput, dutyInput, salaryInput,
            searchTextField;
    private JLabel titleLabel;

    public FriendFind() {
        panel = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        panel.setLayout(gridbag);

        // Title label
        titleLabel = new JLabel("朋友查询结果信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20)); // Font settings
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

        JLabel[] labels = {
                new JLabel("姓名"), new JLabel("性别"), new JLabel("出生年月"),
                new JLabel("家庭地址"), new JLabel("所在公司"),
                new JLabel("职位"), new JLabel("薪水")
        };

        nameInput = new JTextField(15);
        sexInput = new JTextField(15);
        birthdayInput = new JTextField(15);
        addressInput = new JTextField(15);
        companyInput = new JTextField(15);
        dutyInput = new JTextField(15);
        salaryInput = new JTextField(15);

        JTextField[] textFields = { sexInput, birthdayInput, addressInput, companyInput, dutyInput, salaryInput };
        // Set all JTextFields with the same size
        Dimension commonSize = new Dimension(150, nameInput.getPreferredSize().height);
        for (JTextField textField : textFields) {
            textField.setPreferredSize(commonSize);
        }

        // Adding components to the panel using GridBagLayout
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // Padding for components

        // Title label
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 4; // Title spans across 4 columns
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(20, 5, 15, 5); // Top padding
        addComponent(titleLabel, gbc);

        // Labels and input fields
        for (int i = 0; i < labels.length; i++) {
            gbc.gridwidth = 1;
            gbc.insets = new Insets(5, 5, 5, 5); // Default padding

            // Add labels (aligned to the right)
            gbc.gridx = (i < 4) ? 0 : 2; // Left or right column
            gbc.gridy = (i < 4) ? i + 1 : i - 3;
            gbc.anchor = GridBagConstraints.EAST;
            addComponent(labels[i], gbc);

            // Add input fields (aligned to the left)
            gbc.gridx = (i < 4) ? 1 : 3; // Corresponding input fields
            gbc.anchor = GridBagConstraints.WEST;
            if (i == 0) { // First field is the name input
                addComponent(nameInput, gbc);
            } else {
                addComponent(textFields[i - 1], gbc);
            }
        }

        JLabel titleLabel1 = new JLabel("查询系统");
        titleLabel1.setFont(new Font("微软雅黑", Font.BOLD, 20)); // Font settings
        titleLabel1.setHorizontalAlignment(SwingConstants.CENTER);
        gbc.gridx = 0;
        gbc.gridy = 9; // Place it below the existing input fields
        gbc.gridwidth = 4;
        gbc.anchor = GridBagConstraints.CENTER;
        addComponent(titleLabel1, gbc);

        // Adding the new "按姓名查询" label and text field for searching
        JLabel searchLabel = new JLabel("按姓名查询:");
        searchTextField = new JTextField(15);

        gbc.gridx = 0;
        gbc.gridy = 10; // Place it below the existing input fields
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(searchLabel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 10;
        gbc.gridwidth = 2; // Spanning 2 columns for the search field
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(searchTextField, gbc);

        // Adding the search button next to the search text field
        JButton searchButton = new JButton("查询");
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                queryClassmateInfo(searchTextField.getText());
            }
        });

        gbc.gridx = 3;
        gbc.gridy = 10;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(searchButton, gbc);
    }

    // Method to add components to the panel
    private void addComponent(Component c, GridBagConstraints constraints) {
        panel.add(c, constraints);
    }

    private void queryClassmateInfo(String name) {
        // Creating an instance of ClassMateStore to interact with the database
        FriendStore store = new FriendStore();
        Connection conn = store.getConnection();

        if (conn == null) {
            JOptionPane.showMessageDialog(panel, "无法连接到数据库", "数据库连接错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // SQL query to fetch the classmate data based on the name input
        String query = "SELECT * FROM friend WHERE name = ?";

        try (PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, name); // Set the input name as parameter
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                // Populate the JTextFields with the data from the database
                nameInput.setText(rs.getString("name"));
                sexInput.setText(rs.getString("sex"));
                birthdayInput.setText(rs.getString("birthday"));
                addressInput.setText(rs.getString("address"));
                companyInput.setText(rs.getString("company"));
                dutyInput.setText(rs.getString("duty"));
                salaryInput.setText(rs.getString("salary"));
            } else {
                // If no result found
                JOptionPane.showMessageDialog(panel, "未找到该同学信息", "查询结果", JOptionPane.INFORMATION_MESSAGE);
                resetFields();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(panel, "查询失败: " + e.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void resetFields() {
        nameInput.setText("");
        sexInput.setText("");
        birthdayInput.setText("");
        addressInput.setText("");
        companyInput.setText("");
        dutyInput.setText("");
        salaryInput.setText(""); // Clear the name field
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("朋友查询系统");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 500); // Increased size for extra components
        frame.setLocationRelativeTo(null);

        // Initialize and add ClassMateFind panel
        FriendFind friendFind = new FriendFind();
        frame.add(friendFind.panel);

        frame.setVisible(true);
    }
}
朋友持久化类:FriendStore.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class FriendStore {
    public Vector<Friend> getFriend(Connection conn, String sql) {
        Vector<Friend> v = new Vector<>();
        try (Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                Friend friend = new Friend(rs.getString("name"));
                friend.setSex(rs.getString("sex"));
                friend.setBirthday(rs.getString("birthday"));
                friend.setAddress(rs.getString("address"));
                friend.setCompany(rs.getString("company"));
                friend.setDuty(rs.getString("duty"));
                friend.setSalary(rs.getString("salary"));
                friend.setTel(rs.getString("tel"));
                friend.setPhone(rs.getString("phone"));
                v.add(friend);
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return v;
    }

    public Friend getObject(Connection conn, String name) {
        Friend friend = null;
        try (Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("select * from friend where name='" + name + "'")) {
            while (rs.next()) {
                friend = new Friend(rs.getString("name"));
                friend.setSex(rs.getString("sex"));
                friend.setBirthday(rs.getString("birthday"));
                friend.setAddress(rs.getString("address"));
                friend.setCompany(rs.getString("company"));
                friend.setDuty(rs.getString("duty"));
                friend.setSalary(rs.getString("salary"));
                friend.setTel(rs.getString("tel"));
                friend.setPhone(rs.getString("phone"));
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return friend;
    }

    public Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/combook";
        String user = "root";
        String password = "root";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // 更新驱动类名
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
添加朋友面板:AddFriend.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
public class AddFriend extends JPanel {

    private static final long serialVersionUID = 17L;
    private JTextField[] textFields;
    private DefaultComboBoxModel<String> model;

    public AddFriend() {
        this.setLayout(new java.awt.GridBagLayout());

        //
        model = new DefaultComboBoxModel<>();

        // 创建标题
        JLabel titleLabel = new JLabel("添加朋友信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setHorizontalAlignment(SwingConstants.CENTER);

        // 定义标签和输入框
        String[] labelNames = {
                "姓名", "性别", "出生年月", "家庭地址", "个人联系方式",
                "所在公司", "职位", "薪水", "家庭电话"
        };

        JLabel[] labels = new JLabel[labelNames.length];
        textFields = new JTextField[labelNames.length];

        for (int i = 0; i < labelNames.length; i++) {
            labels[i] = new JLabel(labelNames[i] + ":");
            textFields[i] = new JTextField(15);
        }

        JButton addButton = new JButton("添加朋友信息");

        // 布局组件
        GridBagConstraints gbc = new GridBagConstraints();

        // 添加标题
        gbc.gridx = 0;
        gbc.gridy = 0; // 位于第 0 行
        gbc.gridwidth = 5; // 跨越 4 列,确保它占据整个窗口宽度
        gbc.anchor = GridBagConstraints.CENTER; // 居中对齐
        gbc.fill = GridBagConstraints.HORIZONTAL; // 水平方向填充
        gbc.insets = new Insets(10, 0, 25, 0); // 上下间距,增强美观
        add(titleLabel, gbc);

        for (int i = 0; i < labels.length; i++) {
            gbc.insets = new Insets(5, 5, 5, 5);
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridwidth = 1; // 单独占 1 列
            // 添加 JLabel (右对齐)
            gbc.gridx = (i < 5) ? 0 : 2; // 左列或右列
            gbc.gridy = (i < 5) ? i + 1 : i - 4;
            gbc.anchor = GridBagConstraints.EAST; // 右对齐
            add(labels[i], gbc);

            // 添加输入控件 (左对齐)
            gbc.gridx = (i < 5) ? 1 : 4; // 左列或右列对应的控件
            gbc.anchor = GridBagConstraints.WEST; // 左对齐
            add(textFields[i], gbc);

        }

        // 添加按钮
        gbc.gridx = 0;
        gbc.gridy = labelNames.length + 1;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        add(addButton, gbc);

        // 添加按钮事件监听
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (validateInputs()) {
                    addFriendToDatabase();
                }
            }
        });
    }

    /**
     * 将同学信息保存到数据库
     */
    private void addFriendToDatabase() {
        String[] values = getTextFieldValues();
        FriendService service = new FriendService();
        if (service.addFriend(values)) {
            updateFriendInfo(values);
            JOptionPane.showMessageDialog(this, "添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            // ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose();

        } else {
            JOptionPane.showMessageDialog(this, "添加失败,请重试。", "失败", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateFriendInfo(String[] values) {
        // 确保 ClassMateInfo 中的组件已初始化
        if (FriendInfo.nameinput == null) {
            FriendInfo.nameinput = new JComboBox<>(model);
        }
        if (FriendInfo.sexyinput == null) {
            FriendInfo.sexyinput = new JTextField();
        }
        if (FriendInfo.sexyinput == null) {
            FriendInfo.sexyinput = new JTextField();
        }
        if (FriendInfo.birthdayinput == null) {
            FriendInfo.birthdayinput = new JTextField();
        }
        if (FriendInfo.addressinput == null) {
            FriendInfo.addressinput = new JTextField();
        }
        if (FriendInfo.companyinput == null) {
            FriendInfo.companyinput = new JTextField();
        }
        if (FriendInfo.dutyinput == null) {
            FriendInfo.dutyinput = new JTextField();
        }
        if (FriendInfo.salaryinput == null) {
            FriendInfo.salaryinput = new JTextField();
        }

        Friend friend = new Friend(values[0]);
        friend.setName(values[0]);
        friend.setSex(values[1]);
        friend.setBirthday(values[2]);
        friend.setAddress(values[3]);
        friend.setTel(values[7]);
        friend.setCompany(values[5]);
        friend.setDuty(values[5]);
        friend.setSalary(values[6]);
        friend.setPhone(values[8]);

        Vector<Friend> friendVector = new Vector<>();
        friendVector.add(friend);

        FriendInfo.nameinput.addItem(values[0]);
        FriendInfo.nameinput.setSelectedItem(values[0]);
        FriendInfo.sexyinput.setText(values[1]);
        FriendInfo.birthdayinput.setText(values[2]);
        FriendInfo.addressinput.setText(values[3]);
        FriendInfo.companyinput.setText(values[4]);
        FriendInfo.dutyinput.setText(values[5]);
        FriendInfo.salaryinput.setText(values[6]);
    }

    private String[] getTextFieldValues() {
        String[] values = new String[textFields.length];
        for (int i = 0; i < textFields.length; i++) {
            values[i] = textFields[i].getText().trim();
        }

        // 调整界面输入与数据库字段顺序不一致
        String temp = values[4];
        values[4] = values[5];
        values[5] = values[6];
        values[6] = values[7];
        values[7] = temp;
        return values;
    }

    private boolean validateInputs() {
        for (JTextField textField : textFields) {
            if (textField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写所有必填项!", "输入错误", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("添加朋友信息");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new AddFriend());
        frame.setVisible(true);
    }

}

class FriendService {
    private static final String INSERT_SQL = "INSERT INTO friend (name, sex, birthday, address, company, duty, salary, tel, phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

    public boolean addFriend(String... values) {
        try (Connection conn = new FriendStore().getConnection();
                PreparedStatement stmt = conn.prepareStatement(INSERT_SQL)) {

            for (int i = 0; i < values.length; i++) {
                stmt.setString(i + 1, values[i]);
            }

            return stmt.executeUpdate() > 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
删除朋友类:DelFriend.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class DelFriend {
    public DelFriend() {
        String name = FriendInfo.nameinput.getSelectedItem().toString();
        FriendStore friendStore = new FriendStore();
        try (Connection conn = friendStore.getConnection();
                PreparedStatement stmt = conn.prepareStatement("delete from friend where name = ?")) {
            stmt.setString(1, name);
            int rowsAffected = stmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "删除失败,请重试。", "失败", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库操作失败,请重试。", "失败", JOptionPane.ERROR_MESSAGE);
        } finally {
            FriendInfo.nameinput.removeItem(name);
        }

    }
}
修改朋友类:UpdateFriend.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class UpdateFriend {
    FriendStore friendStore = new FriendStore();
    Connection conn = friendStore.getConnection();

    public UpdateFriend() {
        try (PreparedStatement pstmt = conn.prepareStatement(
                "UPDATE friend SET sex = ?, address=?, birthday=?,duty=?,salary=?,company=? where name = ?")) {

            String sex = FriendInfo.sexyinput.getText();
            String name = FriendInfo.nameinput.getSelectedItem().toString();
            String address = FriendInfo.addressinput.getText();
            String birthday = FriendInfo.birthdayinput.getText();
            String duty = FriendInfo.dutyinput.getText();
            String salary = FriendInfo.salaryinput.getText();
            String company = FriendInfo.companyinput.getText();

            pstmt.setString(1, sex);
            pstmt.setString(2, address);
            pstmt.setString(3, birthday);
            pstmt.setString(4, duty);
            pstmt.setString(5, salary);
            pstmt.setString(6, company);
            pstmt.setString(7, name);

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "修改成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "未找到匹配的记录!", "失败", JOptionPane.ERROR_MESSAGE);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "发生错误:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
4. 系统类
自定义容器面板:TabPane.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class TabPane extends JPanel {

    public JPanel panel1;
    public JPanel panel2;
    public JPanel panel3;
    public JPanel panel4;
    public JPanel panel5;
    public JTabbedPane tabbedPane;

    public TabPane() {

        tabbedPane = new JTabbedPane();
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3 = new JPanel();
        panel4 = new JPanel();
        panel5 = new JPanel();

        tabbedPane.addTab("panel1", panel1);
        tabbedPane.setEnabledAt(0, true);
        tabbedPane.setTitleAt(0, "基本信息");

        tabbedPane.addTab("panel2", panel2);
        tabbedPane.setEnabledAt(1, true);
        tabbedPane.setTitleAt(1, "照片");

        tabbedPane.addTab("panel3", panel3);
        tabbedPane.setEnabledAt(2, true);
        tabbedPane.setTitleAt(2, "兴趣爱好");

        tabbedPane.addTab("panel4", panel4);
        tabbedPane.setEnabledAt(3, true);
        tabbedPane.setTitleAt(3, "日常系统");

        tabbedPane.addTab("panel5", panel5);
        tabbedPane.setEnabledAt(4, true);
        tabbedPane.setTitleAt(4, "评价");

        tabbedPane.setTabPlacement(javax.swing.JTabbedPane.TOP);
        tabbedPane.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);

        setLayout(new java.awt.BorderLayout());
        add(tabbedPane, java.awt.BorderLayout.CENTER);
        tabbedPane.setVisible(true);

    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("TabbedPaneDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.add(new TabPane());
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);

    }
}
版本面板:VersionPanel.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class VersionPanel extends JPanel {
    // 使用常量管理界面文字
    private static final String TITLE = "通讯录系统版本信息";
    private static final String VERSION_TEXT = "当前版本: 1.0";
    private static final String AUTHOR_TEXT = "作者: 东北小哥";

    // 布局间距统一管理
    private static final Insets COMPONENT_INSETS = new Insets(5, 10, 5, 10);

    public VersionPanel() {
        initComponents();
    }

    private void initComponents() {
        setLayout(new GridBagLayout());
        setPreferredSize(new Dimension(300, 200));
        GridBagConstraints gbc = createDefaultConstraints();

        // 标题标签(居中显示)
        JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        addComponent(titleLabel, gbc, 0, 0, 2, 1); // 跨两列

        // 版本信息(左对齐)
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(new JLabel(VERSION_TEXT), gbc, 0, 1, 1, 1);

        // 作者信息(左对齐)
        gbc.anchor = GridBagConstraints.WEST;
        addComponent(new JLabel(AUTHOR_TEXT), gbc, 0, 2, 1, 1);
    }

    // 创建默认布局约束
    private GridBagConstraints createDefaultConstraints() {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.NONE; // 水平扩展
        gbc.insets = COMPONENT_INSETS;
        gbc.weightx = 0;
        gbc.weighty = 0;
        return gbc;
    }

    // 增强的组件添加方法
    private void addComponent(Component comp, GridBagConstraints gbc,
            int x, int y, int width, int height) {
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = width;
        gbc.gridheight = height;
        add(comp, gbc);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("版本信息窗口");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 200);
            frame.setLocationRelativeTo(null);

            // 使用面板并添加样式
            VersionPanel panel = new VersionPanel();
            panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            frame.add(panel);

            frame.setVisible(true);
        });
    }
}
帮助窗口:HelpSystem.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
public class HelpSystem extends JFrame {
    private static final int WIDTH = 700;
    private static final int HEIGHT = 400;
    private static final Dimension PREFERRED_SCROLL_SIZE = new Dimension(200, HEIGHT);

    private final JTree navigationTree = new JTree();
    private final JTextArea contentArea = new JTextArea();
    private DefaultMutableTreeNode rootNode;

    public HelpSystem() {
        configureFrameSettings();
        initializeUIComponents();
    }

    private void configureFrameSettings() {
        setTitle("通讯录系统帮助文档");
        setSize(WIDTH, HEIGHT);
        setLocationRelativeTo(null);
    }

    private void initializeUIComponents() {
        rootNode = createNavigationStructure();
        navigationTree.setModel(new DefaultTreeModel(rootNode));
        navigationTree.addMouseListener(new NavigationListener());

        JSplitPane mainSplitter = createMainSplitter(
                createScrollableNavigationPanel(),
                createContentPanel());

        getContentPane().add(mainSplitter);
    }

    private DefaultMutableTreeNode createNavigationStructure() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("通讯录系统帮助文档");

        addCategoryNodes(root,
                new String[] { "同学", "同事", "朋友" },
                new String[][] {
                        { "信息模块", "通讯模块" },
                        { "信息模块", "通讯模块" },
                        { "信息模块", "通讯模块" }
                });

        root.add(createQuerySystemNode());
        return root;
    }

    private void addCategoryNodes(DefaultMutableTreeNode root, String[] categories, String[][] subItems) {
        for (int i = 0; i < categories.length; i++) {
            DefaultMutableTreeNode categoryNode = new DefaultMutableTreeNode("如何操作" + categories[i] + "通讯系统");
            for (String subItem : subItems[i]) {
                categoryNode.add(new DefaultMutableTreeNode("如何使用" + categories[i] + subItem));
            }
            root.add(categoryNode);
        }
    }

    private DefaultMutableTreeNode createQuerySystemNode() {
        return new DefaultMutableTreeNode("如何操作查询系统");
    }

    private JScrollPane createScrollableNavigationPanel() {
        JScrollPane scrollPane = new JScrollPane(navigationTree);
        scrollPane.setPreferredSize(PREFERRED_SCROLL_SIZE);
        return scrollPane;
    }

    private JComponent createContentPanel() {
        contentArea.setEditable(false);
        contentArea.setLineWrap(true);
        contentArea.setWrapStyleWord(true);
        return new JScrollPane(contentArea);
    }

    private JSplitPane createMainSplitter(Component left, Component right) {
        JSplitPane splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
        splitter.setOneTouchExpandable(true);
        splitter.setContinuousLayout(true);
        splitter.setDividerSize(3);
        splitter.setDividerLocation(200);
        return splitter;
    }

    private class NavigationListener extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            TreePath path = navigationTree.getPathForLocation(e.getX(), e.getY());
            if (path != null) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                if (!node.isRoot()) {
                    showHelpContent(node.getUserObject().toString());
                }
            }
        }

        private void showHelpContent(String nodeName) {
            contentArea.setText("如需获取关于 [" + nodeName + "] 的详细使用说明,请查阅随附的电子文档或安装光盘中的帮助手册。");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new HelpSystem().setVisible(true));
    }
}
5. 表结构
classmate
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
CREATE TABLE `classmate`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `homeaddress` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `city` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `company` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `duty` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `salary` double(20, 3) NOT NULL,
  `contact` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `homephone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 86 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
company
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
CREATE TABLE `company`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `department` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `birthday` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `duty` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `salary` double(20, 3) NOT NULL,
  `tel` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `motel` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 45 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
friend
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
CREATE TABLE `friend`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `birthday` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `company` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `duty` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `salary` double(20, 3) NOT NULL,
  `tel` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `phone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 48 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

总结

本章重点,使用所学知识,完成实际案例,实现一个通讯录系统。至此,JavaSwingGUI 从小白到大神系列博文结束,感谢你的阅读亦可在下方留言交流。