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

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

zhezhongyun 2025-04-30 21:17 26 浏览

接上一篇《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<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

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

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<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

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

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<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

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

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("如何操作" + 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

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

相关推荐

DevExpress使用教程:GridView经验小结

下面是笔者自己总结的使用DevExpressGridview的一些经验小结,分享给大家:1、去除GridView头上的"Dragacolumnheaderheretogroup...

ComponentOne 新版本发布,新增 .NET 6 和 Blazor 平台控件支持

ComponentOneEnterprise是葡萄城推出的一款内置300多种开发控件的.NET控件集,可满足WinForm、WPF、Blazor、ASP.NETMVC等平台下的系统开发...

Wijmo5 Flexgrid基础教程:数据绑定

WijmoEnterprise下载>FlexGrid在JavaScript程序中启动添加Wijmo引用;添加wijmo控件的扩展;在JavaScript中初始化wijmo控件;(可选)添加cs...

Wijmo5 Flexgrid基础教程:InlineEdit

WijmoEnterprise下载>对于flexgrid,可以直接在单元格内进行编辑。但另外还有一种编辑方式,即在一行添加按钮,统一的编辑和提交数据。本文主要介绍给flexgrid添加编辑按钮...

WinForms Data Grid控件升级(winform devexpress控件)

告诉大家一个好消息:慧都将于近期隆重推出“DevExpress14.2新版发布会”。心动不如行动,赶快报名吧!我们期待与您相约DevExpress14.2新版发布会。>>新增Wind...

XAML控件宽度为另一控件的一半、静态属性绑定

控件上当某些数据需要根据其他数据的变化而变化很多时候,想让某个控件的宽度或者高度是另一个已有控件的一半,一开始打算使用ObjectDataProvider来实现,因为在控件上当某些数据需要根据其他数据...

用 CSS Grid 布局制作一个响应式柱状图

最新一段时间比较喜欢玩弄图表,出于好奇,我想找出比较好的用CSS制作图表的方案。开始学习网上开源图表库,它对我学习新的和不熟悉的前端技术很有帮助,比如这个:CSSGrid。今天和大家分享我学到的...

Grid 移动端双列瀑布流(移动端瀑布流布局)

预览图:原理合理使用Grid的属性:display:设置为grid指明当前容器为Grid布局grid-template-columns:定义每一列的列宽(百分比或绝对单位)grid-templa...

DevExpress导出GridControl控件数据

前言:使用C#做桌面应用时,我们会常常使用Winform作为我们的开发界面,但是windows自带的控件由于长时间不更新,已经不能够满足当前开发需要所以使用DevExpress控件作为Winform...

css grid 布局的那些事儿(css grid布局和flex布局)

CSSGrid是一种为Web开发创建网站布局的方式。它已经存在了很多年,随着更多浏览器的支持,它终于变得越来越流行。接下来我们将了解下CSSGrid及其工作原理。了解下它如何使用。CSS...

Grid.js - 跨框架的前端表格插件(前端table框架)

只想简简单单画个表格,但React,Vue,Angular,…,这么多前端框架,各自都有不同的表格渲染库。就没有表格库能“一次画表,到处运行”吗?来看看Grid.js这个跨框架的前端表格插件吧!...

WPF开发教程01-布局控件(wpf tablecontrol控件)

布局控件是用于进行控件布局的容器类控件,其内部控件按照一定规律自动排列,且在父控件改变大小时,会自动适应。常用布局控件如下:1.一维布局控件(StackPanel)其内部控件按照某个维度自动排列,排...

wxPython - 高级控件之表格Grid(wxpython grid刷新数据)

实战wxPython系列-043wx.grid.Grid及其相关类用于显示和编辑表格数据。它们提供了一组丰富的功能,用于显示、编辑和与各种数据源交互。wx.grid.Grid是一个功能强大的但是又稍微...

前端 BFC、IFC、GFC 和 FFC,这些你都知道吗?

如果觉得我的文章不错,可以关注我,想要看其他的进阶知识可以查看我发布过的文章!编辑搜图请点击输入图片描述BFC(Blockformattingcontexts):块级格式上下文页面上的一个隔离的...

20多个好用的 Vue 组件库,请查收

在本文中,我们将探讨一些最常见的vuejs组件。你可以收藏一波。VueTables-2地址:https://github.com/matfish2/vue-tables-2VueTables2...