百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

JavaSwingGUI从小白到大神-6(续)(java从小白到大牛)

cac55 2025-03-24 14:17 16 浏览 0 评论

接上一篇《JavaSwingGUI从小白到大神-6》,因本篇文章3万多字,头条一篇发不完,只能分开发。


同事查询面板:CompanyFind.java

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

public Vector getCompany(Connection conn, String sql) {
        Vector 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

public class AddCompany extends JPanel {

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

    public AddCompany() {
        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()) {
                    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 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.setstringi 1 valuesi return stmt.executeupdate> 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }
}

删除同事类:DelCompany.java

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

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

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

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

        // 创建 DefaultComboBoxModel
        DefaultComboBoxModel 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 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

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 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 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 loadClassMateData() {
        Vector 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

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

public class FriendStore {
    public Vector getFriend(Connection conn, String sql) {
        Vector 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

public class AddFriend extends JPanel {

    private static final long serialVersionUID = 17L;
    private JTextField[] textFields;
    private DefaultComboBoxModel 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 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.setstringi 1 valuesi return stmt.executeupdate> 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }
}

删除朋友类:DelFriend.java

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

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

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

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

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 categoriesi for string subitem : subitemsi categorynode.addnew defaultmutabletreenode categoriesi subitem root.addcategorynode private defaultmutabletreenode createquerysystemnode return new defaultmutabletreenode private jscrollpane createscrollablenavigationpanel jscrollpane scrollpane='new' jscrollpanenavigationtree scrollpane.setpreferredsizepreferred_scroll_size return scrollpane private jcomponent createcontentpanel contentarea.seteditablefalse contentarea.setlinewraptrue contentarea.setwrapstylewordtrue return new jscrollpanecontentarea private jsplitpane createmainsplittercomponent left component right jsplitpane splitter='new' jsplitpanejsplitpane.horizontal_split left right splitter.setonetouchexpandabletrue splitter.setcontinuouslayouttrue splitter.setdividersize3 splitter.setdividerlocation200 return splitter private class navigationlistener extends mouseadapter override public void mousepressedmouseevent e treepath path='navigationTree.getPathForLocation(e.getX(),' e.gety if path defaultmutabletreenode node='(DefaultMutableTreeNode)' path.getlastpathcomponent if node.isroot showhelpcontentnode.getuserobject.tostring private void showhelpcontentstring nodename contentarea.settext nodename public static void mainstring args swingutilities.invokelater -> new HelpSystem().setVisible(true));
    }
}

5. 表结构

classmate

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

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

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 从小白到大神系列博文结束,感谢你的阅读亦可在下方留言交流。

相关推荐

上网行为管理有什么用,行为审计软件解决方案?

上网行为管理有什么用,行为审计软件解决方案?我们生活在互联网的时代,网络是比较复杂的,有时候经常会出现一些网络违规现象,这时候就可以进行上网行为管理了,现在有很多的公司都会进行上网行为管理,因为这样可...

上网行为管理软件如何监控员工访问网址信息

上网行为管理软件可以通过域之盾软件来监控员工访问的网址信息:主要方式↓1、网页日志记录上网行为管理软件可以通过网页日志记录功能,完整地记录员工在工作中访问的所有网站,包括访问时间、访问页面、访问方式等...

企业如何确保上网行为管理顺利进行?

企业的稳定长久发展离不开对员工的上网行为管理,因为员工的上网行为关乎到工作效率、生产效率、以及重要的数据信息安全问题。一旦有不规范的上网行为,便容易造成企业终端数据泄密事件,对企业造成重大的财产损失以...

员工上网行为监控如何实现?六个妙招!帮你轻松管理员工上网!

员工上网行为不仅关乎个人工作效率,更直接影响到企业的信息安全和整体运营。不当的上网行为,如访问非法网站、泄露公司机密、长时间闲聊等,都可能给企业带来不可估量的损失。因此,监控员工上网行为,不仅是为了提...

终端管理系统规范企业上网行为管理

企业内部经常会遇到不同的上网行为管理问题,如职员在上班时间炒股、打游戏、上网聊天等不正当的上网行为,用U盘、硬盘等移动设备随意拷贝资料,终端资产难以管理等,降低办公效率的同时,也增加了企业内部泄密风...

企业如何进行上网行为管理?_如何管理企业网络

企业如何进行上网行为管理?为了保障网络安全,提高员工工作效率,企业有必要部署上网行为管理。上网行为管理可对企业内部员工的上网行为进行全方位有效管理,保护Web访问安全,降低互联网使用风险,避免机密信息...

演员赵露思的官方微博注销的原因是什么?

根据多方权威媒体报道及平台验证,演员赵露思的微博账号已于2025年8月19日正式注销。目前搜索该账号显示“因用户自行申请关闭,现已无法查看”。这一结果源于她8月13日在直播中宣布的注销决定,当时她直言...

分手传闻仅4月,关晓彤的一张海边亲吻照,撕碎了鹿晗最后的体面

“原来八年真能被四个月的‘海边吻照’一键清空。”热搜上那张模糊的侧脸一贴,评论瞬间爆炸:关晓彤亲的是李昀锐,鹿晗的生日祝福还停留在去年。八年,够让一部剧从开播到大结局,也够让一对顶流情侣把微博背景换成...

计算机基础知识(五)(3)_计算机基础知识100道

四、如何使用计算机4、软件的通用使用方法计算机发展到现在,正常使用时均采用窗口式界面。我们的介绍不涉及苹果机。操作系统从DOS(DOS阶段有两类,一类是微软的,称为MS—DOS;另一类称为PC—DOS...

笔记本的这些基础知识,你再不知道,就真的被社会淘汰了!

请您在阅读前点击上面的“关注”二字,后续会为您提供更多有价值的电脑知识,感谢每一位朋友的支持!这篇文章依然是给大家讲讲关于笔记本电脑的基础知识,新手小白可一定要收藏起来,以后想看的时候可以找出来就看,...

电脑基础知识,引起电脑故障的原因

引起电脑出现故障的原因非常多,概括来说主要包括以下几个方面的问题。操作不当:操作不当是指误删除文件或非法关机等不当操作。操作不当通常会造成电脑程序无法运行或电脑无法启动,修复此类故障,只要将删除或损坏...

笔记本电脑新手使用教程,笔记本电脑使用技巧

学电脑能够快速入门是每个新手梦寐以求的事情,但是不是每个人都能快速入门的。但是如果定制好合理计划,循序渐进,就会收到非常好的效果。今天小编来跟大家说说笔记本电脑新手教程的详细介绍-装机吧,大家一起...

电脑基础知识:(二)电脑主机_电脑主机组成图解

你好!我是麦秋~前言现代生活随着互联网通讯的快速发展,通讯技术日趋完美,应用软件日益普及,电脑的使用与维护则成为人们日常生活中密不可分的、重要的生活内容。电脑恐怕是中老年人的短板,然而又是急需解决的问...

电脑基础知识:(六)电脑应用程序_电脑的应用程序是什么意思

你好!我是麦秋~应用软件是专为解决一些具体问题的软件,是体现电脑用途的部分,种类繁多,如:办公软件、游戏软件、杀毒软件等;自媒体平台上的西瓜、头条、抖音、剪映等,对于上述软件主要是操作和使用上的问题,...

键盘操作方法大全_键盘操作教程

【键盘操作方法大全】键盘可不仅仅能帮我们打字哦,还有很多快捷的操作你都知道吗?除了Ctrl+C、Ctrl+V以外,再多学几种吧,让你用起电脑来十指如飞~别再慢慢用鼠标点了,用开始键+Tab键切换程序让...

取消回复欢迎 发表评论: