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

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

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

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

相关推荐

字体缩放(方式一)(字体缩放150%怎么做)

通过元素宽度和字数计算得到缩放简单实现如下:/***字体最大为视觉要求大小(maxFontSize);超出缩小字体显示,最小为minFontSize;最小字体时超出部分使用圆点(...);*p...

网页世界隐藏的神秘代码语言,竟能这样改变布局

CSS基础:选择器与属性CSS(CascadingStyleSheets)是用于控制网页外观的一门样式表语言。它通过定义HTML元素的显示方式来增强网页的表现力。CSS的选择器允许开发者精确地定位...

CSS属性值计算过程详解(css属性用来定义元素计算)

在CSS中,即使某些属性没有显式声明,浏览器也会通过**属性值计算过程**为每个元素的所有属性赋予最终值。这一过程分为四个关键步骤,以下将逐一解析。1.确定声明值浏览器首先检查所有**直接应用**到...

软网推荐:找回调整Windows 10字号功能

之前的系统,从WindowsXP到早期版本的Windows10,均有字体大小调整功能,但从创意者版Windows10以来,取消了之前的设置选项,取而代之的是自定义缩放比例设置。使用这个功能调整过...

Excel中如何设置文本框属性,实例代码讲解

Excel不仅可以对数据进行处理,而且也可以图形化数据,直观显示数据表达的内容。本节介绍一个很重要的对象,Characters,字符对象,使用Characters对象可修改包含在全文本字符串中的任...

CSS 字体样式(css中字体)

本节我们来讲字体样式,之前我们学习HTML的时候学过一些用于字体加粗、倾斜的标签,但是使用标签来实现的效果肯定没有我们通过CSS中的样式来的方便。接下来我们会给大家介绍下面这几个属性的使用:通...

PC网站建设必备代码知识:HTML基础与应用技巧

在PC网站建设的相关课程里,代码扮演着至关重要的角色。只有熟练运用正确的代码,我们才能打造出功能完善、用户体验出色的PC网站。接下来,我会详细讲解在PC网站建设环节中必须了解的代码知识。HTML基础代...

让你大跌眼镜的疯狂 HTML 和 CSS 技巧

今天,分享一个让你大开眼界的技巧。通过使用这个技巧,你可以将整个网页变成一个CSS编辑器。没错,你从未见过这种方法。当我第一次尝试时,我完全被震惊到了。现在,让我们开始吧!步骤1首先,创建一个基础的...

jQuery EasyUI使用教程:创建一个链接按钮

jQueryEasyUI最新版下载>本教程主要为大家展示如何使用jQueryEasyUI创建一个链接按钮。通常情况下,使用“button/”元素来创建一个按钮;使用“a/”元素来创建链接按钮...

React 19 有哪些新特性?(react100)

如果你对React18还不熟悉,欢迎阅读之前的文章《React18全览[1]》最近React发布了V19RC版本,按照惯例,我们对React19的新特性进行一次深度的体验学习...

Java注解探秘:为什么@PostConstruct能解决你的初始化难题?

你是否在Spring项目中遇到过这样的困扰:明明依赖注入已经完成,但某些配置就是无法正常加载?手动调用初始化方法又容易引发空指针异常?这就是@PostConstruct注解大显身手的时候了!@Post...

AI驱动的表单自动填写(ai置入表格)

我们都同意,填写表格是一项枯燥且耗时的任务。如果我们可以创建一个可以为我们填写表格的AI助手,让我们将时间投入到更有建设性的任务中,那会怎样?AI助手将能够通过调用以表单字段为参数的函数来填写表...

从零到一:小程序设计新手如何快速上手?

开发环境搭建对于小程序设计新手而言,搭建合适的开发环境是首要任务。以小程序为例,其官方提供了功能强大的开发工具——开发者工具。首先,新手需前往官方开发者平台,在页面中找到“工具下载”板块,根据...

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

接上一篇《JavaSwingGUI从小白到大神-6》,因本篇文章3万多字,头条一篇发不完,只能分开发。同事查询面板:CompanyFind.javapublicclassCompanyFind{...

C# winform界面假死(c#程序假死)

针对C#WinForm界面假死问题,以下是分步解决方案:1.使用异步编程(async/await)将耗时操作移至后台线程,保持UI线程响应。步骤:将事件处理函数标记为async。使用Task....