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

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

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

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


同事查询面板:CompanyFind.java

public class CompanyFind {
    static JPanel panel;
    private JTextField nameInput, codeInput, sexInput, departmentInput, birthdayInput, addressInput, dutyInput,
            salaryInput, searchTextField;
    private JLabel titleLabel;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        frame.setVisible(true);
    }
}

同事持久化类:CompanyStore.java

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

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

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

    public Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/combook";
        String user = "root";
        String password = "root";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // 更新驱动类名
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

添加同事面板:AddCompany.java

public class AddCompany extends JPanel {

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

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

        model = new DefaultComboBoxModel();

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

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

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

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

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

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

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

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

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

        }

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

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

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

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

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

    private void updateCompanyInfo(String[] values) {

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

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

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

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

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

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

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

}

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

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

            for (int i = 0; i < values.length i stmt.setstringi 1 valuesi return stmt.executeupdate> 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }
}

删除同事类:DelCompany.java

public class DelCompany {

    public DelCompany() {
        String name = CompanyInfo.nameinput.getSelectedItem().toString();
        CompanyStore companyStore = new CompanyStore();
        try (Connection conn = companyStore.getConnection();
                PreparedStatement stmt = conn.prepareStatement("delete from company where name = ?")) {
            stmt.setString(1, name);
            int rowsAffected = stmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "删除失败,请重试。", "失败", JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库操作失败,请重试。", "失败", JOptionPane.INFORMATION_MESSAGE);
        } finally {
            CompanyInfo.nameinput.removeItem(name);
        }
    }
}

修改同事类:UpdateCompany.java

public class UpdateCompany {
    CompanyStore companyStore = new CompanyStore();
    Connection conn = companyStore.getConnection();

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

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

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

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "修改成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "未找到匹配的记录!", "失败", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "发生错误:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}

3. 朋友相关类

朋友类:Friend.java

public class Friend {

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

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

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

    public String getBirthday() {
        return birthday;
    }

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

    public String getAddress() {
        return address;
    }

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

    public String getCompany() {
        return company;
    }

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

    public String getDuty() {
        return duty;
    }

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

    public String getSalary() {
        return salary;
    }

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

    public String getTel() {
        return tel;
    }

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

    public String getPhone() {
        return phone;
    }

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

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

}

朋友信息面板:FriendInfo.java

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

朋友联系面板:FriendCommunication.java

public class FriendCommunication extends JPanel {

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

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

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

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

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

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

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

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

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

朋友查询面板:FriendFind.java

public class FriendFind {
    static JPanel panel;
    private JTextField nameInput, sexInput, birthdayInput, addressInput, companyInput, dutyInput, salaryInput,
            searchTextField;
    private JLabel titleLabel;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        frame.setVisible(true);
    }
}

朋友持久化类:FriendStore.java

public class FriendStore {
    public Vector getFriend(Connection conn, String sql) {
        Vector v = new Vector<>();
        try (Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                Friend friend = new Friend(rs.getString("name"));
                friend.setSex(rs.getString("sex"));
                friend.setBirthday(rs.getString("birthday"));
                friend.setAddress(rs.getString("address"));
                friend.setCompany(rs.getString("company"));
                friend.setDuty(rs.getString("duty"));
                friend.setSalary(rs.getString("salary"));
                friend.setTel(rs.getString("tel"));
                friend.setPhone(rs.getString("phone"));
                v.add(friend);
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return v;
    }

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

    public Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/combook";
        String user = "root";
        String password = "root";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // 更新驱动类名
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

添加朋友面板:AddFriend.java

public class AddFriend extends JPanel {

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

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

        //
        model = new DefaultComboBoxModel<>();

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

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

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

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

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

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

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

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

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

        }

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

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

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

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

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

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

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

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

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

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

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

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

}

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

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

            for (int i = 0; i < values.length i stmt.setstringi 1 valuesi return stmt.executeupdate> 0;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }
}

删除朋友类:DelFriend.java

public class DelFriend {
    public DelFriend() {
        String name = FriendInfo.nameinput.getSelectedItem().toString();
        FriendStore friendStore = new FriendStore();
        try (Connection conn = friendStore.getConnection();
                PreparedStatement stmt = conn.prepareStatement("delete from friend where name = ?")) {
            stmt.setString(1, name);
            int rowsAffected = stmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "删除失败,请重试。", "失败", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库操作失败,请重试。", "失败", JOptionPane.ERROR_MESSAGE);
        } finally {
            FriendInfo.nameinput.removeItem(name);
        }

    }
}

修改朋友类:UpdateFriend.java

public class UpdateFriend {
    FriendStore friendStore = new FriendStore();
    Connection conn = friendStore.getConnection();

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

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

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

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

        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "发生错误:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}

4. 系统类

自定义容器面板:TabPane.java

public class TabPane extends JPanel {

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

    public TabPane() {

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

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

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

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

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

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

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

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

    }

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

    }
}

版本面板:VersionPanel.java

public class VersionPanel extends JPanel {
    // 使用常量管理界面文字
    private static final String TITLE = "通讯录系统版本信息";
    private static final String VERSION_TEXT = "当前版本: 1.0";
    private static final String AUTHOR_TEXT = "作者: 东北小哥";

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

    public VersionPanel() {
        initComponents();
    }

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

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

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

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

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

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

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

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

            frame.setVisible(true);
        });
    }
}

帮助窗口:HelpSystem.java

public class HelpSystem extends JFrame {
    private static final int WIDTH = 700;
    private static final int HEIGHT = 400;
    private static final Dimension PREFERRED_SCROLL_SIZE = new Dimension(200, HEIGHT);

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

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

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

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

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

        getContentPane().add(mainSplitter);
    }

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

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

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

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

5. 表结构

classmate

CREATE TABLE `classmate`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `homeaddress` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `city` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `company` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `duty` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `salary` double(20, 3) NOT NULL,
  `contact` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `homephone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 86 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

company

CREATE TABLE `company`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `department` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `birthday` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `duty` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `salary` double(20, 3) NOT NULL,
  `tel` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `motel` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 45 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

friend

CREATE TABLE `friend`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `birthday` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `company` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `duty` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `salary` double(20, 3) NOT NULL,
  `tel` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `phone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 48 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

总结

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

相关推荐

无力吐槽的自动续费(你被自动续费困扰过吗?)

今天因为工作需要,需要在百度文库上下载一篇文章。没办法,确实需要也有必要,只能老老实实的按要求买了个VIP。过去在百度文库上有过类似经历,当时为了写论文买了一个月的VIP,后面也没有太注意,直到第二个...

百度文库推出“文源计划”创作者可一键认领文档

11月7日,百度文库发布了旨在保护创作者权益的“文源计划”。所谓“文源计划”,即为每一篇文档找到源头,让创作者享受更多的权益。据百度文库总经理李小婉介绍,文源计划分为三部分,分别是版权认证、版权扶持和...

有开放大学学号的同学,百度文库高校版可以用了。

还在网上找百度文库的下载方式,只要从身边的朋友在读开放大学的,那他(她)的学号就可以登陆到国家开放大学图书馆,还使用百度文库高校版来下载。与百度文库稍有不同,但足够使用了。现转国图链接如下:htt...

搜索资源方法推荐(搜索资源的方法)

今天msgbox就要教大家如何又快又准的搜到各类资源,第一点,排除干扰百度搜索出来啊经常前排展示它的产品以及百度文库,如何去除呢?很简单,后面输入空格减号百度文库,比如你搜高等数学百度文库很多,只要后...

一行代码搞定百度文库VIP功能(2021百度文库vip账号密码共享)

百度文库作为大家常用查资料找文档的平台,大多数文档我们都可以直接在百度文库找到,然而百度文库也有让人头痛的时候。好不容易找到一篇合适的文档,当你准备复制的时候他却提示你需要开通VIP才能复制~~~下载...

百度文库文档批量上传工具用户说明书

百度文库文档批量上传工具用户说明书1、软件主要功能1、批量上传文档到百度文库,支持上传到收费、VIP专享、优享以及共享。2、支持自动分类和自动获取标签3、支持多用户切换,一个账户传满可以切换到...

百度文库现在都看不到文档是否上传成功,要凉了吗?

打开知识店铺,百度文库文档里显示都是下载这一按键,上传的文档也看不到是否成功?咋情况,要取消了吗?没通过审核的也不让你删除,是几个意思,想通吃吗?现在百度上传文档也很费劲,有时弄了半天的资料上传审核过...

微信推广引流108式:利用百度文库长期分享软文引流

百度文库相对于百度知道、百度百科来说,操作上没那么多条条框框,规则上也相对好把握些。做一条百度知道所花费的精力一般都会比做一条百度文库的要多些,老马个人操作下来觉得百度文库更好把握。但见仁见智吧,今天...

职场“避雷”指南 百度文库推出标准化劳动合同范本

轰轰烈烈的毕业季结束了,众多应届生在经过了“职场海选”后,已正式成为职场生力军的一员。这一阶段,除了熟悉业务,签订劳动合同、了解职场福利也迅速被提上日程。而随着国人法律意识的增强,百度文库内《劳动合同...

《百度文库》:素材精选宝库(百度文库官网首页)

《百度文库》:独特功能助力选择高质量素材在当今信息爆炸的时代,如何高效地获取并利用有价值的素材成为了许多人面临的挑战。而《百度文库》作为百度公司推出的一款在线文档分享平台,凭借其丰富的资源、强大的功能...

深度整合和开放AI能力 百度文库和网盘推出内容操作系统「沧舟OS」

【TechWeb】4月25日消息,Create2025百度AI开发者大会上,百度文库和百度网盘推出全球首个内容操作系统——沧舟OS。基于沧舟OS,百度文库APP全新上线「GenFlow超能搭子」...

女子发现大二作业被百度文库要求付费下载,律师:平台侵权,应赔偿

近日,28岁的黎女士在百度百科搜索家乡的小地名时,发现了自己在大二完成的课题作业。她继续搜索,发现多个平台收录了该文,比如豆丁网和文档之家等,有的还设置了付费或积分下载。2月15日,九派新闻记者以用户...

2016杀入百度文库的新捷径,只有少数人才知道的喔

百度的产品在SEO优化中的分量真不用多说,其实很多人都像我一样一直在找捷径。但是我经常发现很多人都是在用死方法。比如发贴吧发帖而不知道去申请一个吧主,知道自问自答而不知道去申请一个合作资格。口碑和贴吧...

百度文库付费文档搜索方法(百度文库付费文档搜索方法有哪些)

一直以来,百度文库中无论是个人中心还是个人主页,都没有像淘宝一样的店内搜索功能,连最近新开的知识店铺也没有设计店内搜索功能,这无论是对上传用户还是下载用户都不方便,上传用户想要搜索自己的文档无法办到...

供读者免费使用!泰达图书馆机构版百度文库新年上新啦

在泰达图书馆读者使用百度文库数字资源不需要VIP,免-费-用!惊不惊喜?快来了解一下吧……新年伊始,为满足区域企业、高校、科研院所以及居民群众在教学、科研及学习过程中,对各类文献资源的需求,泰达图书馆...

取消回复欢迎 发表评论: