Java实训日志07

八、项目开发实现步骤

(十)创建应用程序类

  • 创建应用程序类,存在全局数据,所有的窗口界面都可以共享应用程序类里存放的数据。

1、创建app子包

  • net.sxx.student根包里创建app子包
    在这里插入图片描述

2、创建Application类

  • net.sxx.student.app包里创建Application
    在这里插入图片描述
package net.sxx.student.app;

/**
 * 功能:应用程序类,存放全局变量
 * 作者:孙希霞
 * 日期:2023年06月16日
 */
public class Application {
    public static int id; // 登录用户标识符
    public static String username; // 登录用户名
    public static String password; // 登录用户密码
    public static LoginFrame loginFrame; // 登录窗口
    public static MainFrame mainFrame; // 主窗口
    public static RegisterFrame registerFrame;// 注册窗口
    
}

  • 此时,三个窗口界面类还未创建,因此程序会报错:无法解析符号
    在这里插入图片描述
  • net.sxx.student根包里创建gui子包(gui:graphical user initerface - 图形用户界面),在里面创建三个类:LoginFrame、MainFrame、与RegisterFrame。
    在这里插入图片描述
  • 此时,Application类就不会报错
    在这里插入图片描述

(十一)创建窗口界面类

1、创建主界面窗口

-先来做一个空白的主界面窗口

  • 继承JFrame类
    在这里插入图片描述
  • 添加构造方法(带标题参数的构造方法)
    在这里插入图片描述
  • 声明变量
  • 定义状态服务变量
    在这里插入图片描述
  • 创建初始化图形用户界面 - initGUI
    在这里插入图片描述
  • 在构造方法里调用initGUI()方法
    在这里插入图片描述
  • 编写主方法,实例化主窗口
    在这里插入图片描述
  • 运行程序,查看结果,窗口启动时屏幕居中
    在这里插入图片描述
  • 单击主窗口关闭按钮,窗口倒是关闭了,但是程序依然在运行
    在这里插入图片描述
  • 修改一下initGUI()方法
    在这里插入图片描述
  • 运行程序,查看效果
    请添加图片描述
  • 退出时弹出消息框询问对象
  • 如果希望单击关闭按钮后,弹出一个询问框,询问用户是否要退出系统,那么就不用采用上述方法,而应该采用注册 窗口监听器的方法,通过编写事件处理方法来弹出询问对话框。
    在这里插入图片描述
  • 注册窗口监听器,创建一个窗口适配器,编写事件处理代码
    在这里插入图片描述
  • 运行程序,查看结果请添加图片描述

2、创建用户登录窗口

  • 继承JFrame,创建LoginFrame
    在这里插入图片描述
  • 创建初始化图形用户界面方法
    在这里插入图片描述
  • 添加单构造方法
    在这里插入图片描述
  • 添加主方法,实例化用户登录窗口
    在这里插入图片描述
  • 运行程序,查看结果

请添加图片描述

  • 空白的用户窗口,不能调整大小
    在这里插入图片描述

  • 声明用户登录窗口所需变量
    在这里插入图片描述

  • 实例化组件
    在这里插入图片描述

  • 将控件添加到小面板,然后将小面板添加到主面板
    在这里插入图片描述

  • 设置按钮热键字母,以及密码框的回显字符
    在这里插入图片描述

  • 运行程序,查看效果
    在这里插入图片描述

  • 行间距太大,界面显得不紧凑,怎么设置窗口属性,才能让界面紧凑好看呢?很简单,调用窗口的pack()方法即可。
    在这里插入图片描述

  • 运行程序,查看结果
    在这里插入图片描述

  • 单击【确定】按钮,或当焦点落在【确定】按钮时按回车键,都会调用登录方法login()
    在这里插入图片描述

  • 编写用户登录login()。

 private void login(){
        // 获取用户名
        username = txtUsername.getText().trim();
        // 获取密码
        password = new String(txtPassword.getPassword());

        // 创建用户服务对象
        UserService userService = new UserServiceImpl();
        // 调用登录方法,返回登录用户对象
        User user = userService.login(username, password);

        // 判断登录用户是否为空,决定登录是否成功
        if (user != null) {
            // 隐藏登录窗口
            Application.loginFrame.setVisible(false);
            // 定义状态服务对象
            StatusService statusService = new StatusServiceImpl();
            // 获取状态对象
            Status status = statusService.findStatusById(1);
            // 保存登录用户的信息
            Application.id = user.getId();
            Application.username = user.getUsername();
            Application.password = user.getPassword();
            // 提示用户登录成功
            JOptionPane.showMessageDialog(null,
                    "欢迎使用学生信息管理系统" + status.getVersion(),
                    "用户登录", JOptionPane.INFORMATION_MESSAGE);
            // 显示系统主窗口
            Application.mainFrame = new MainFrame("");
            // 释放登录窗口
            Application.loginFrame.dispose();
        } else {
            // 隐藏登录窗口
            Application.loginFrame.setVisible(false);
            // 提示用户登录失败,要重新输入用户名或密码
            JOptionPane.showMessageDialog(null,
                    "用户名或密码错误,请重新输入!",
                    "用户登录", JOptionPane.ERROR_MESSAGE);
            // 显示登录窗口
            Application.loginFrame.setVisible(true);
            // 用户名文本框内容全选
            txtUsername.selectAll();
            // 密码文本框内容全选
            txtPassword.selectAll();
            // 用户名文本框获取焦点
            txtUsername.requestFocus();
        }
    }
  • 运行程序,查看结果
    请添加图片描述

  • 输入用户名之后,敲回车让光标跳到密码文本框,就应该编写一个用户名文本框的按键事件。
    在这里插入图片描述

  • 编写【密码】文本框按键事件处理代码(敲回车后执行登录方法)
    在这里插入图片描述

  • 编写【取消】按钮单击事件处理代码
    在这里插入图片描述

  • 编写【注册】按钮单击事件处理代码
    在这里插入图片描述

  • 此时,需要修改用户注册窗口RegisterFrame,继承JFrame,添加单参构造方法,初始化图形用户界面方法,主方法
    在这里插入图片描述

  • 再查看用户登录窗口【注册】按钮单击事件处理代码,就没有错误了。
    在这里插入图片描述

  • 运行程序,查看效果
    请添加图片描述

  • 登录窗口,完整代码

package net.sxx.student.gui;

import net.sxx.student.app.Application;
import net.sxx.student.bean.Status;
import net.sxx.student.bean.User;
import net.sxx.student.service.StatusService;
import net.sxx.student.service.UserService;
import net.sxx.student.service.impl.StatusServiceImpl;
import net.sxx.student.service.impl.UserServiceImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月16日
 */

public class LoginFrame extends JFrame {

    private String username;
    private String password;

    private JLabel lbIUsername;
    private JLabel lbIPassword;
    private JTextField txtUsername;
    private JPasswordField txtPassword;

    private JButton btnOK;
    private JButton btnCancel;
    private JButton btnRegister;

    private JPanel panel,panel1,panel2,panel3;


    public LoginFrame(String title){
        super(title);
        initGUI();
    }
    private void initGUI(){
        // 实例化组件(面板与控件)
        panel = (JPanel) getContentPane();
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3= new JPanel();

        lbIUsername = new JLabel("用户名:");
        lbIPassword = new JLabel("密  码:");
        txtUsername = new JTextField(15);
        txtPassword = new JPasswordField(15);
        btnOK = new JButton("确定[0]");
        btnCancel = new JButton("取消[C]");
        btnRegister = new JButton("注册[R]");

        // 将控件添加到三个小面板
        panel1.add(lbIUsername);
        panel1.add(txtUsername);
        panel2.add(lbIPassword);
        panel2.add(txtPassword);
        panel3.add(btnOK);
        panel3.add(btnCancel);
        panel3.add(btnRegister);

        // 设置主面板为三行一列的网络布局
        panel.setLayout(new GridLayout(3,1));
        // 将三个小面板一次添加到主面板
        panel.add(panel1);
        panel.add(panel2);
        panel.add(panel3);

        // 设置按钮热键字母
        btnOK.setMnemonic(KeyEvent.VK_0);
        btnCancel.setMnemonic(KeyEvent.VK_C);
        btnRegister.setMnemonic(KeyEvent.VK_R);
        // 设置密码框回显字符
        txtPassword.setEchoChar('*');


        // 设置窗口的大小
        setSize(250,200);
        // 设置窗口屏幕居中
        setLocationRelativeTo(null);
        // 设置窗口不可调整大小
        setResizable(false);
        // 设置窗口刚好容纳组件
        pack();
        // 设置窗口可见
        setVisible(true);
        // 设置窗口默认关闭操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 单击【确定】按钮单击事件处理
        btnOK.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                login();
            }
        });

        // 【确定】按钮事件处理
        btnOK.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e){
                // 按下回车键,调用登录方法
                if (e.getKeyCode() == KeyEvent.VK_ENTER){
                    login();
                }
            }
        });

        // 【用户名】文本框按键事件处理
        txtUsername.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                // 判断是否按下回车健
                if (e.getKeyCode() == KeyEvent.VK_ENTER){
                    // 让密码文本框获取焦点
                    txtPassword.requestFocus();
                }
            }
        });

        // 【密码】文本框按键事件处理
        txtPassword.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                // 判断是否按了回车键
                if (e.getKeyCode() == KeyEvent.VK_ENTER){
                    login();
                }
            }
        });

        // 【取消】
        btnCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        // 【注册】按钮单击事件处理代码
        btnRegister.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Application.loginFrame.setVisible(false);
                Application.registerFrame=new RegisterFrame("用户注册");

            }
        });
    }



    private void login(){
        // 获取用户名
        username = txtUsername.getText().trim();
        // 获取密码
        password = new String(txtPassword.getPassword());

        // 创建用户服务对象
        UserService userService = new UserServiceImpl();
        // 调用登录方法,返回登录用户对象
        User user = userService.login(username, password);

        // 判断登录用户是否为空,决定登录是否成功
        if (user != null) {
            // 隐藏登录窗口
            Application.loginFrame.setVisible(false);
            // 定义状态服务对象
            StatusService statusService = new StatusServiceImpl();
            // 获取状态对象
            Status status = statusService.findStatusById(1);
            // 保存登录用户的信息
            Application.id = user.getId();
            Application.username = user.getUsername();
            Application.password = user.getPassword();
            // 提示用户登录成功
            JOptionPane.showMessageDialog(null,
                    "欢迎使用学生信息管理系统" + status.getVersion(),
                    "用户登录", JOptionPane.INFORMATION_MESSAGE);
            // 显示系统主窗口
            Application.mainFrame = new MainFrame("");
            // 释放登录窗口
            Application.loginFrame.dispose();
        } else {
            // 隐藏登录窗口
            Application.loginFrame.setVisible(false);
            // 提示用户登录失败,要重新输入用户名或密码
            JOptionPane.showMessageDialog(null,
                    "用户名或密码错误,请重新输入!",
                    "用户登录", JOptionPane.ERROR_MESSAGE);
            // 显示登录窗口
            Application.loginFrame.setVisible(true);
            // 用户名文本框内容全选
            txtUsername.selectAll();
            // 密码文本框内容全选
            txtPassword.selectAll();
            // 用户名文本框获取焦点
            txtUsername.requestFocus();
        }
    }


    public static void main(String[] args) {
        Application.loginFrame = new LoginFrame("用户登录");
    }
}

3、创建用户注册窗口RegisterFrame

  • 在创建用户登录窗口过程中,已经创建了一个可以显示与关闭的空白注册窗口
    在这里插入图片描述
  • 单参构造方法
    在这里插入图片描述
  • 初始化图形用户界面方法
    在这里插入图片描述
  • 主方法
    在这里插入图片描述
  • 申明变量
    在这里插入图片描述
  • 创建组件(面板与控件)
    在这里插入图片描述
  • 将控件添加到四个小面板
    在这里插入图片描述
  • 置大面板布局,将四个小面板添加到大面板
    在这里插入图片描述
  • 设置窗口刚好容纳组件
    在这里插入图片描述
  • 在initGUI()方法里编写【提交】按钮事件处理代码
    在这里插入图片描述
  • 编写注册方法register()
private void register(){
        // 获取用户名
        username = txtUsername.getText().trim();
        // 获取密码
        password = new String(txtPassword.getPassword());
        // 获取电话
        telephone = txtTelephone.getText().trim();
        // 定义当前时间为注册时间
        registerTime = new Timestamp(System.currentTimeMillis());

        // 对用户名进行非空校验
        if (username.equals("")) {
            JOptionPane.showMessageDialog(null, "用户名不能为空!",
                    "学生信息管理系统", JOptionPane.WARNING_MESSAGE);
            txtUsername.requestFocus();
            return;
        }

        // 对密码进行非空校验
        if (password.equals("")) {
            JOptionPane.showMessageDialog(null, "密码不能为空!",
                    "学生信息管理系统", JOptionPane.WARNING_MESSAGE);
            txtPassword.requestFocus();
            return;
        }

        // 定义用户服务对象
        UserService userService = new UserServiceImpl();
        // 创建用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setTelephone(telephone);
        user.setRegisterTime(registerTime);

        // 添加用户
        int count = userService.addUser(user);

        // 判断是否添加成功
        if (count > 0) {
            setVisible(false);
            JOptionPane.showMessageDialog(null, "恭喜!注册成功!",
                    "学生信息管理系统", JOptionPane.INFORMATION_MESSAGE);
            setVisible(true);
        } else {
            JOptionPane.showMessageDialog(null, "遗憾!注册失败!",
                    "学生信息管理系统", JOptionPane.INFORMATION_MESSAGE);
        }
    }
  • 在initGUI()方法里编写【取消】按钮单击事件处理代码
    在这里插入图片描述

  • 在initGUI()方法里编写【登录】文本框按键事件处理代码
    在这里插入图片描述

  • 在initGUI()方法里编写【用户名】文本框按键事件处理代码
    在这里插入图片描述

  • 在initGUI()方法里编写【密码】文本框按键事件处理代码
    在这里插入图片描述

  • 在initGUI()方法里编写【电话】文本框按键事件处理代码
    在这里插入图片描述

  • 先启动登录窗口,单击【注册】按钮,跳转到注册窗口,注册一个新用户,然后以新用户登录系统。
    请添加图片描述

  • 利用注册窗口,我们注册一个名叫“无心剑”的新用户,然后利用“无心剑”登录系统,测试取得成功。

  • 注册窗口完整代码

package net.sxx.student.gui;

import net.sxx.student.app.Application;
import net.sxx.student.bean.User;
import net.sxx.student.service.UserService;
import net.sxx.student.service.impl.UserServiceImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Timestamp;
import java.util.Date;


/**
 * 功能:注册窗口
 * 作者:孙希霞
 * 日期:2023年06月16日
 */
public class RegisterFrame extends JFrame {

    // 声明变量
    private JLabel lblUsername;
    private JLabel lblPassword;
    private JLabel lblTelephone;

    private JTextField txtUsername;
    private JTextField txtTelephone;
    private JPasswordField txtPassword;

    private JButton btnSubmit;
    private JButton btnCancel;
    private JButton btnLogin;

    private JPanel panel;
    private JPanel panel1;
    private JPanel panel2;
    private JPanel panel3;
    private JPanel panel4;

    private String username;
    private String password;
    private String telephone;
    private Date registerTime;


    public RegisterFrame(String title) {
        super(title);
        initGUI();
    }

    private void initGUI() {

        // 创建组件
        panel=(JPanel)getContentPane();
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3 = new JPanel();
        panel4 = new JPanel();

        lblUsername = new JLabel("用户名:");
        lblPassword = new JLabel("密  码:");
        lblTelephone = new JLabel("电  话:");
        txtUsername = new JTextField("",15);
        txtPassword = new JPasswordField("",15);
        txtTelephone = new JTextField("",15);
        btnSubmit = new JButton("提交[S]");
        btnCancel = new JButton("取消[C]");
        btnLogin = new JButton("登录[L]");

        // 将控件添加到四个小面板
        panel1.add(lblUsername);
        panel1.add(txtUsername);
        panel2.add(lblPassword);
        panel2.add(txtPassword);
        panel3.add(lblTelephone);
        panel3.add(txtTelephone);
        panel4.add(btnSubmit);
        panel4.add(btnCancel);
        panel4.add(btnLogin);

        // 设置大面板布局,将四个小面板添加到大面板
        panel.setLayout(new GridLayout(4,1));
        panel.add(panel1);
        panel.add(panel2);
        panel.add(panel3);
        panel.add(panel4);

        // 设置窗口大小
        setSize(250,200);
        setLocationRelativeTo(null);
        setResizable(false);
        // 设置窗口刚好容纳组件
        pack();
        setTitle("用户注册");
        setVisible(true);


        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                dispose();
                Application.loginFrame.setVisible(true);
            }
        });

        // 【提交】按钮单击事件处理
        btnSubmit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                register();
            }
        });

        // 【提交】按钮按键事件处理
        btnSubmit.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e){
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    register();
                }
            }
        });

        // 【取消】按钮单击事件
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 显示登录窗口
                Application.loginFrame.setVisible(true);
                // 卸载当前窗口
                dispose();
            }
        });

        // 【登录】按钮单击事件处理
        btnLogin.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0){
                Application.loginFrame.setVisible(true);
                dispose();
            }
        });

        // 【用户名】 文本框按键事件处理
        txtUsername.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER){
                    txtPassword.requestFocus();
                }
            }
        });

        // 【密码】文本框按键事件处理
        txtPassword.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 10){
                    txtTelephone.requestFocus();
                }
            }
        });

        // 【电话】文本框按键事件处理
        txtTelephone.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER){
                    btnSubmit.requestFocus();
                }
            }
        });

    }
    private void register(){
        // 获取用户名
        username = txtUsername.getText().trim();
        // 获取密码
        password = new String(txtPassword.getPassword());
        // 获取电话
        telephone = txtTelephone.getText().trim();
        // 定义当前时间为注册时间
        registerTime = new Timestamp(System.currentTimeMillis());

        // 对用户名进行非空校验
        if (username.equals("")) {
            JOptionPane.showMessageDialog(null, "用户名不能为空!",
                    "学生信息管理系统", JOptionPane.WARNING_MESSAGE);
            txtUsername.requestFocus();
            return;
        }

        // 对密码进行非空校验
        if (password.equals("")) {
            JOptionPane.showMessageDialog(null, "密码不能为空!",
                    "学生信息管理系统", JOptionPane.WARNING_MESSAGE);
            txtPassword.requestFocus();
            return;
        }

        // 定义用户服务对象
        UserService userService = new UserServiceImpl();
        // 创建用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setTelephone(telephone);
        user.setRegisterTime(registerTime);

        // 添加用户
        int count = userService.addUser(user);

        // 判断是否添加成功
        if (count > 0) {
            setVisible(false);
            JOptionPane.showMessageDialog(null, "恭喜!注册成功!",
                    "学生信息管理系统", JOptionPane.INFORMATION_MESSAGE);
            setVisible(true);
        } else {
            JOptionPane.showMessageDialog(null, "遗憾!注册失败!",
                    "学生信息管理系统", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public static void main(String[] args){
        Application.registerFrame = new RegisterFrame("用户注册");
    }
}

4、创建设置学校信息窗口SetCollegeInfoFrame

  • net.sxx.student.gui包里创建SetCollegeInfoFrame
    在这里插入图片描述
package net.sxx.student.gui;

import net.sxx.student.bean.College;
import net.sxx.student.service.CollegeService;
import net.sxx.student.service.impl.CollegeServiceImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 功能:设置学校信息
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class SetCollegeInfoFrame extends JFrame{
    JPanel panel;
    JPanel pnlNorth;
    JPanel panel1;
    JPanel panel2;
    JPanel panel3;
    JPanel panel4;
    JPanel panel5;
    JPanel pnlCenter;
    JPanel pnlSouth;

    JLabel lblName;
    JLabel lblPresident;
    JLabel lblStartTime;
    JLabel lblTelephone;
    JLabel lblEmail;
    JLabel lblAddress;
    JLabel lblProfile;

    JButton btnSave;
    JButton btnExit;

    JTextField txtName;
    JTextField txtPresident;
    JTextField txtStartTime;
    JTextField txtTelephone;
    JTextField txtEmail;
    JTextField txtAddress;
    JTextArea txtProfile;

    JScrollPane scrollPane;

    private CollegeService collegeService;
    private College college;
    private int id=1;
    public SetCollegeInfoFrame(String title){
        super(title);
        initGUI();
    }
    private void initGUI() {
        panel = (JPanel) getContentPane();
        pnlNorth = new JPanel();
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3 = new JPanel();
        panel4 = new JPanel();
        panel5 = new JPanel();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        lblName = new JLabel("学校名称:");
        lblPresident = new JLabel("校    长:");
        lblStartTime = new JLabel("建校时间:");
        lblTelephone = new JLabel("联系电话:");
        lblEmail = new JLabel("电子邮箱:");
        lblAddress = new JLabel("通讯地址:");
        lblProfile = new JLabel("学校简介:");

        txtName = new JTextField(30);
        txtPresident = new JTextField(11);
        txtStartTime = new JTextField(12);
        txtTelephone = new JTextField(11);
        txtEmail = new JTextField(12);
        txtAddress = new JTextField(30);
        txtProfile = new JTextArea(5,37);
        txtProfile.setLineWrap(true);
        scrollPane = new JScrollPane(txtProfile,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        btnSave = new JButton("保存[S]");
        btnSave.setMnemonic(KeyEvent.VK_S);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.setLayout(new BorderLayout());
        panel.add(pnlNorth,"North");
        panel.add(pnlCenter,"Center");
        panel.add(pnlSouth,"South");


        pnlNorth.setLayout(new GridLayout(5, 1));
        pnlNorth.add(panel1);
        pnlNorth.add(panel2);
        pnlNorth.add(panel3);
        pnlNorth.add(panel4);
        pnlNorth.add(panel5);

        // 将控件依次添加到五个小面板
        panel1.add(lblName);
        panel1.add(txtName);
        panel2.add(lblPresident);
        panel2.add(txtPresident);
        panel2.add(lblStartTime);
        panel2.add(txtStartTime);
        panel3.add(lblTelephone);
        panel3.add(txtTelephone);
        panel3.add(lblEmail);
        panel3.add(txtEmail);
        panel4.add(lblAddress);
        panel4.add(txtAddress);
        panel5.add(lblProfile);

        pnlCenter.add(scrollPane);

        pnlSouth.add(btnSave);
        pnlSouth.add(btnExit);

        collegeService = new CollegeServiceImpl();
        college = collegeService.findCollegeById(id);
        // 利用学校属性值设置相应控件的内容
        txtName.setText(college.getName());
        txtPresident.setText(college.getPresident());
        txtStartTime.setText(college.getStartTime().toString());
        txtEmail.setText(college.getEmail());
        txtAddress.setText(college.getAddress());
        txtProfile.setText(college.getProfile());

        // 设置窗口大小
        setSize(450,350);
        // 设置窗口屏幕居中
        setLocationRelativeTo(null);
        // 设置窗口不可调整大小
        setResizable(false);
        // 设置窗口刚好容纳组件
        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // 【关闭】 按钮单击事件处理
        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });

        // 【保存按钮】单击事件处理
        btnSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                try{
                    college.setName(txtName.getText());
                    college.setPresident(txtPresident.getText());
                    college.setStartTime(new Timestamp(
                            new SimpleDateFormat("yyyy-MM-dd")
                                    .parse(txtStartTime.getText().toString()).getTime()));

                    college.setEmail(txtEmail.getText());
                    college.setAddress(txtAddress.getText());
                    college.setProfile(txtProfile.getText());
                    collegeService.updateCollege(college);
                    JOptionPane.showMessageDialog(null,"更新数据成功!");
                } catch (ParseException e) {
                    JOptionPane.showMessageDialog(null,"更新数据失败!");
                }
            }
        });
    }
    public static void main(String[] args){
        new SetCollegeInfoFrame("设置学校信息");
    }
}

  • 运行程序,查看结果
    请添加图片描述

5、创建修改用户密码窗口ChangePasswordFrame

  • 在net.sxx.student.gui包里创建ChangePasswordFrame类
    在这里插入图片描述
    在这里插入图片描述
  • 准备修改id = 1 的记录的密码
package net.sxx.student.gui;

import net.sxx.student.app.Application;
import net.sxx.student.bean.User;
import net.sxx.student.service.UserService;
import net.sxx.student.service.impl.UserServiceImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class ChangePasswordFrame extends JFrame {
    private JPanel panel;
    private JPanel pnlRow1;
    private JPanel pnlRow2;
    private JPanel pnlRow3;
    private JPanel pnlRow4;
    private JPanel pnlRow5;

    private JLabel lblUsername;
    private JLabel lblPassword;
    private JLabel lblNewPassword1;
    private JLabel lblNewPassword2;

    private JTextField txtUsername;
    private JPasswordField txtPassword;
    private JPasswordField txtNewPassword1;
    private JPasswordField txtNewPassword2;

    private JButton btnOK;
    private JButton btnCancel;

    private UserService userService;

    public ChangePasswordFrame(String title) {
        super(title);
        initGUI();
    }

    private void initGUI() {
        panel = (JPanel) getContentPane();
        pnlRow1 = new JPanel();
        pnlRow2 = new JPanel();
        pnlRow3 = new JPanel();
        pnlRow4 = new JPanel();
        pnlRow5 = new JPanel();

        lblUsername = new JLabel("用户名:");
        lblPassword = new JLabel("旧密码:");
        lblNewPassword1 = new JLabel("新密码:");
        lblNewPassword2 = new JLabel("确    认:");

        txtUsername = new JTextField(20);
        txtUsername.setEditable(false);
        txtPassword = new JPasswordField(20);
        txtNewPassword1 = new JPasswordField(20);
        txtNewPassword2 = new JPasswordField(20);

        btnOK = new JButton("确定[O]");
        btnOK.setMnemonic(KeyEvent.VK_O);
        btnCancel = new JButton("取消[C]");
        btnCancel.setMnemonic(KeyEvent.VK_C);

        panel.setLayout(new GridLayout(5, 1));
        panel.add(pnlRow1);
        panel.add(pnlRow2);
        panel.add(pnlRow3);
        panel.add(pnlRow4);
        panel.add(pnlRow5);

        pnlRow1.add(lblUsername);
        pnlRow1.add(txtUsername);
        pnlRow2.add(lblPassword);
        pnlRow2.add(txtPassword);
        pnlRow3.add(lblNewPassword1);
        pnlRow3.add(txtNewPassword1);
        pnlRow4.add(lblNewPassword2);
        pnlRow4.add(txtNewPassword2);
        pnlRow5.setLayout(new FlowLayout(FlowLayout.CENTER, 30, 3));
        pnlRow5.add(btnOK);
        pnlRow5.add(btnCancel);

        setResizable(false);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        txtUsername.setEditable(false);
        txtUsername.setText(Application.username);

        btnCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        btnOK.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changePassword();
            }
        });

        btnOK.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 10) {
                    changePassword();
                }
            }
        });

        txtUsername.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    txtPassword.requestFocus();
                }
            }
        });

        txtPassword.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    txtNewPassword1.requestFocus();
                }
            }
        });

        txtNewPassword1.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    txtNewPassword2.requestFocus();
                }
            }
        });

        txtNewPassword2.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    btnOK.requestFocus();
                }
            }
        });
    }

    private void changePassword() {
        // 获取用户信息
        int id = Application.id;
        String username = Application.username;

        String password = new String(txtPassword.getPassword());
        String newPassword1 = new String(txtNewPassword1.getPassword());
        String newPassword2 = new String(txtNewPassword2.getPassword());

        userService = new UserServiceImpl();

        if (userService.login(username, password) == null) {
            JOptionPane.showMessageDialog(null, "旧密码错误,请重新输入!", "错误提示", JOptionPane.ERROR_MESSAGE);
            txtPassword.requestFocus();
            txtPassword.selectAll();
        } else if (newPassword1.equals("")) {
            JOptionPane.showMessageDialog(null, "新密码不能为空!", "错误提示", JOptionPane.ERROR_MESSAGE);
            txtNewPassword1.requestFocus();
        } else if (newPassword2.equals("")) {
            JOptionPane.showMessageDialog(null, "确认密码不能为空!", "错误提示", JOptionPane.ERROR_MESSAGE);
            txtNewPassword2.requestFocus();
        } else if (!newPassword1.equals(newPassword2)) {
            JOptionPane.showMessageDialog(null, "两次密码不一致,请重新输入!", "错误提示", JOptionPane.ERROR_MESSAGE);
            txtNewPassword1.setText("");
            txtNewPassword2.setText("");
            txtNewPassword1.requestFocus();
        } else {
            User user = userService.findUserById(id);
            user.setPassword(newPassword1);
            int count = userService.updateUser(user);
            if (count > 0) {
                JOptionPane.showMessageDialog(null, "密码修改成功!", "设置密码", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(null, "密码修改失败!", "设置密码", JOptionPane.WARNING_MESSAGE);
            }
        }
    }

    public static void main(String[] args) {
        Application.id = 1;
        Application.username = "赛尔号";
        new ChangePasswordFrame("修改用户密码");
    }
}

  • 运行程序,查看效果
    请添加图片描述
  • 在NaviCat里,打开用户表,查看第一条记录的密码是否已经修改,确实已经由原先的000000修改成123123
    在这里插入图片描述

6、创建浏览学生窗口BrowseStudentsFrame

net.sxx.student.gui包里创建BrowseStudentsFrame
在这里插入图片描述

package net.sxx.student.dao.impl;

import net.sxx.student.bean.Status;
import net.sxx.student.bean.Student;
import net.sxx.student.dao.StatusDao;
import net.sxx.student.dao.StudentDao;
import org.junit.Test;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月14日
 */
public class TestStudentDaoImpl {
    // 定义学生数据访问对象
    StudentDao dao = new StudentDaoImpl();

    @Test
    public void testInsert(){
        // 创建学生对象
        Student student = new Student();
        // 设置学生对象属性
        student.setId("22265029");
        student.setName("妮妮");
        student.setSex("女");
        student.setAge(6);
        student.setDepartment("人工智能与大数据学院");
        student.setClazz("22级软件3班");
        student.setTelephone("18383047927");
        // 调用学生数据访问对象的插入方法
        int count = dao.insert(student);
        // 判断学生记录是否插入成功
        if (count > 0){
            System.out.println("恭喜,学生记录插入成功!");
            System.out.println(dao.findById(student.getId()));
        }else {
            System.out.println("遗憾,学生记录插入失败");
        }
    }

    @Test
    public void testDeleteById(){
        String id = "22265051";
        // 调用学生数据访问对象的安id删除方法
        int count = dao.deleteById(id);
        // 判断学生记录是否删除成功
        if (count > 0){
            System.out.println("恭喜,学生记录删除成功!");
        }else {
            System.out.println("遗憾,学生记录删除失败");
        }
    }

    @Test
    public void testDeleteByClass(){
        String clazz = "22级软件3班";
        // 调用学生数据访问对象的按班级删除方法
        int count = dao.deleteByClass(clazz);
        if (count > 0){
            System.out.println("恭喜,["+clazz+"]学生记录删除成功!");
        }else {
            System.out.println("遗憾,[" + clazz + "]学生记录删除失败");
        }
    }

    @Test
    public void testDeleteByDepartment(){
        String department = "人工智能与大数据学院";
        // 调用学生数据访问对象的按系部删除方法
        int count = dao.deleteByDepartment(department);
        if (count > 0){
            System.out.println("恭喜,["+department+"]学生记录删除成功!");
        }else {
            System.out.println("遗憾,[" + department + "]学生记录删除失败");
        }
    }

    @Test
    public void testUpdate() {
        StudentDao studentDao = new StudentDaoImpl();
        Student student = studentDao.findById("22265029");
        System.out.println("更新前:" + student);
        student.setAge(20);
        student.setTelephone("11111000001");
        student.setDepartment("师范学院");
        int count = studentDao.update(student);
        if (count > 0) {
            System.out.println("更新成功!!!");
            System.out.println("更新后:" + studentDao.findById("22265029"));
        } else {
            System.out.println("What a pity!更新失败!!!");
        }
    }

    @Test
    public void testFindById(){
        // 定义标识符变量
        String id = "22265029";
        // 创建状态数据访问接口对象
        StudentDao studentDao = new StudentDaoImpl();
        // 调用按标识符查询状态记录的方法
        Student student = studentDao.findById(id);
        if (student != null) {
            System.out.println(student);
        } else {
            System.out.println("标识符为[" + id + "]的状态不存在");
        }
    }

    @Test
    public void testFindByName(){
        String name = "妮";
        // 调用学生数据访问对象的按姓名查找方法
        List<Student> students = dao.findByName(name);
        // 判断列表里是否有元素
        if (students.size() > 0){
            // 通过增强for循环遍历学生列表
            for (Student student : students){
                System.out.println(student);
            }
        }else {
            System.out.println("温馨提示:查无此人!!!");
        }
    }

    @Test
    public void testFindByClass(){
        String clazz = "22级软件3班";
        // 调用学生数据访问对象的按班级查找方法
        List<Student> students = dao.findByClass(clazz);
        // 判断列表里是否有元素
        if (students.size() > 0){
            // 通过增强for循环遍历学生列表
            for (Student student : students){
                System.out.println(student);
            }
        }else {
            System.out.println("温馨提示:查无此人!!!");
        }
    }

    @Test
    public void testFindByDepartment(){
        String department = "师范学院";
        // 调用学生数据访问对象的按系部查找方法
        List<Student> students = dao.findByDepartment(department);
        // 判断列表里是否有元素
        if (students.size() > 0){
            // 通过增强for循环遍历学生列表
            for (Student student : students){
                System.out.println(student);
            }
        }else {
            System.out.println("温馨提示:查无此人!!!");
        }
    }

    @Test
    public void testFindAll(){
        // 调用学生数据访问对象的查找全部方法
        List<Student> students = dao.findAll();
        // 通过增强for 循环遍历学生列表
         for (Student student : students){
             System.out.println(student);
         }
    }

    @Test
    public void testFindRowsBySex(){
        // 调用学生数据访问对象的按性别统计人数方法
        Vector rows = dao.findRowsBySex();
        // 获取向量的迭代器
        Iterator iterator = rows.iterator();
        // 遍历迭代器
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    @Test
    public void testFindRowsByClass(){
        // 调用学生数据访问对象的按班级统计人数方法
        Vector rows = dao.findRowsByClass();
        // 获取向量的迭代器
        Iterator iterator = rows.iterator();
        // 遍历迭代器
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    @Test
    public void testFindRowsByDepartment(){
        // 调用学生数据访问对象的按系部统计人数方法
        Vector rows = dao.findRowsByDepartment();
        // 获取向量的迭代器
        Iterator iterator = rows.iterator();
        // 遍历迭代器
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

  • 运行程序,查看结果
    请添加图片描述

7、创建添加学生窗口AddStudentFrame

在net.sxx.student.gui包里创建添加学生窗口AddStudentFrame
在这里插入图片描述

package net.sxx.student.gui;

import net.sxx.student.bean.Student;
import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class AddStudentFrame extends JFrame {
    private JPanel panel;
    private JPanel pnlCenter;
    private JPanel pnlRow1;
    private JPanel pnlRow2;
    private JPanel pnlRow3;
    private JPanel pnlRow4;
    private JPanel pnlRow5;
    private JPanel pnlRow6;
    private JPanel pnlRow7;
    private JPanel pnlSouth;

    private JLabel lblId;
    private JLabel lblName;
    private JLabel lblSex;
    private JLabel lblAge;
    private JLabel lblDepartment;
    private JLabel lblClass;
    private JLabel lblTelephone;

    private JTextField txtId;
    private JTextField txtName;
    private JTextField txtSex;
    private JTextField txtAge;
    private JTextField txtDepartment;
    private JTextField txtClass;
    private JTextField txtTelephone;

    private JButton btnExit;
    private JButton btnOK;
    private JButton btnCancel;

    private int currentRow;
    private List<Student> students;

    public AddStudentFrame(String title) {
        super(title);
        initGUI();
    }

    private void initGUI() {
        panel = (JPanel) getContentPane();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        pnlRow1 = new JPanel();
        pnlRow2 = new JPanel();
        pnlRow3 = new JPanel();
        pnlRow4 = new JPanel();
        pnlRow5 = new JPanel();
        pnlRow6 = new JPanel();
        pnlRow7 = new JPanel();

        pnlRow1.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow2.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow3.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow4.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow5.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow6.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow7.setLayout(new FlowLayout(FlowLayout.LEFT));

        lblId = new JLabel("学号:");
        lblName = new JLabel("姓名:");
        lblSex = new JLabel("性别:");
        lblAge = new JLabel("年龄:");
        lblDepartment = new JLabel("系部:");
        lblClass = new JLabel("班级:");
        lblTelephone = new JLabel("电话:");

        txtId = new JTextField(20);
        txtName = new JTextField(20);
        txtSex = new JTextField(20);
        txtAge = new JTextField(20);
        txtDepartment = new JTextField(20);
        txtClass = new JTextField(20);
        txtTelephone = new JTextField(20);
        btnOK = new JButton("确定[O]");
        btnCancel = new JButton("取消[C]");
        btnExit = new JButton("退出[X]");
        btnOK.setMnemonic(KeyEvent.VK_O);
        btnCancel.setMnemonic(KeyEvent.VK_C);
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.setLayout(new BorderLayout());
        panel.add(pnlCenter, BorderLayout.CENTER);
        panel.add(pnlSouth, BorderLayout.SOUTH);
        pnlCenter.setLayout(new GridLayout(7, 1));
        pnlCenter.add(pnlRow1);
        pnlCenter.add(pnlRow2);
        pnlCenter.add(pnlRow3);
        pnlCenter.add(pnlRow4);
        pnlCenter.add(pnlRow5);
        pnlCenter.add(pnlRow6);
        pnlCenter.add(pnlRow7);

        pnlRow1.add(lblId);
        pnlRow1.add(txtId);
        pnlRow2.add(lblName);
        pnlRow2.add(txtName);
        pnlRow3.add(lblSex);
        pnlRow3.add(txtSex);
        pnlRow4.add(lblAge);
        pnlRow4.add(txtAge);
        pnlRow5.add(lblDepartment);
        pnlRow5.add(txtDepartment);
        pnlRow6.add(lblClass);
        pnlRow6.add(txtClass);
        pnlRow7.add(lblTelephone);
        pnlRow7.add(txtTelephone);

        pnlSouth.add(btnOK);
        pnlSouth.add(btnCancel);
        pnlSouth.add(btnExit);

        setSize(500, 300);
        setResizable(false);
        pack();
        setLocationRelativeTo(null);
        setTitle("添加学生记录");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        btnOK.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (txtId.getText().trim().equals("")) {
                    JOptionPane.showMessageDialog(null, "学号不能为空!", "增加学生记录", JOptionPane.WARNING_MESSAGE);
                    txtId.requestFocus();
                    return;
                }

                if (!isNumber(txtAge.getText().trim())) {
                    JOptionPane.showMessageDialog(null, "注意:年龄全由数字构成!", "增加学生记录", JOptionPane.WARNING_MESSAGE);
                    txtAge.setText("");
                    txtAge.requestFocus();
                    return;
                }

                Student student = new Student();
                student.setId(txtId.getText().trim());
                student.setName(txtName.getText().trim());
                student.setSex(txtSex.getText().trim());
                student.setAge(Integer.parseInt(txtAge.getText()));
                student.setDepartment(txtDepartment.getText().trim());
                student.setClazz(txtClass.getText().trim());
                student.setTelephone(txtTelephone.getText().trim());

                StudentService studentService = new StudentServiceImpl();
                int count = studentService.addStudent(student);
                if (count > 0) {
                    JOptionPane.showMessageDialog(null, "添加记录成功!", "增加学生记录", JOptionPane.INFORMATION_MESSAGE);
                    txtId.setText("");
                    txtName.setText("");
                    txtSex.setText("");
                    txtAge.setText("");
                    txtDepartment.setText("");
                    txtClass.setText("");
                    txtTelephone.setText("");
                    txtId.requestFocus();
                } else {
                    JOptionPane.showMessageDialog(null, "添加记录失败!", "增加学生记录", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        btnCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                txtId.setText("");
                txtName.setText("");
                txtSex.setText("");
                txtAge.setText("");
                txtDepartment.setText("");
                txtClass.setText("");
                txtTelephone.setText("");
                txtId.requestFocus();
            }
        });

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        txtId.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (!txtId.getText().trim().equals("")) {
                        txtName.requestFocus();
                    }
                }
            }
        });

        txtName.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    txtSex.requestFocus();
                }
            }
        });

        txtSex.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    txtAge.requestFocus();
                }
            }
        });

        txtAge.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    txtDepartment.requestFocus();
                }
            }
        });

        txtDepartment.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    txtClass.requestFocus();
                }
            }
        });

        txtClass.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    txtTelephone.requestFocus();
                }
            }
        });
    }

    boolean isNumber(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9') {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        new AddStudentFrame("");
    }
}


  • 运行程序,查看结果
    请添加图片描述

8、创建添加学生窗口EditStudentFrame

在net.sxx.student.gui包里创建添加学生窗口EditStudentFrame
在这里插入图片描述

package net.sxx.student.gui;

import net.sxx.student.bean.Student;
import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.List;

/**
 * 功能:浏览学生记录
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class BrowseStudentsFrame extends JFrame {
    private JPanel panel;
    private JPanel pnlCenter;
    private JPanel pnlRow1;
    private JPanel pnlRow2;
    private JPanel pnlRow3;
    private JPanel pnlRow4;
    private JPanel pnlRow5;
    private JPanel pnlRow6;
    private JPanel pnlRow7;
    private JPanel pnlSouth;

    private JLabel lblId;
    private JLabel lblName;
    private JLabel lblSex;
    private JLabel lblAge;
    private JLabel lblDepartment;
    private JLabel lblClass;
    private JLabel lblTelephone;

    private JTextField txtId;
    private JTextField  txtName;
    private JTextField  txtSex;
    private JTextField  txtAge;
    private JTextField  txtDepartment;
    private JTextField  txtClass;
    private JTextField  txtTelephone;

    private JButton btnTop;
    private JButton btnPrevious;
    private JButton btnNext;
    private JButton btnBottom;
    private JButton btnExit;

    private int currentRow;
    private List<Student> students;
    StudentService studentService;

    public BrowseStudentsFrame(String title) {
        super(title);
        initGUI();
    }

    private void initGUI() {
        panel = (JPanel) getContentPane();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        pnlRow1 = new JPanel();
        pnlRow2 = new JPanel();
        pnlRow3 = new JPanel();
        pnlRow4 = new JPanel();
        pnlRow5 = new JPanel();
        pnlRow6 = new JPanel();
        pnlRow7 = new JPanel();

        pnlRow1.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow2.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow3.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow4.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow5.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow6.setLayout(new FlowLayout(FlowLayout.LEFT));
        pnlRow7.setLayout(new FlowLayout(FlowLayout.LEFT));

        lblId = new JLabel("学号:");
        lblName = new JLabel("姓名:");
        lblSex = new JLabel("性别:");
        lblAge = new JLabel("年龄:");
        lblDepartment = new JLabel("系部:");
        lblClass = new JLabel("班级:");
        lblTelephone = new JLabel("电话:");

        txtId = new JTextField(40);
        txtName = new JTextField(40);
        txtSex = new JTextField(40);
        txtAge = new JTextField(40);
        txtDepartment = new JTextField(40);
        txtClass = new JTextField(40);
        txtTelephone = new JTextField(40);
        txtId.setEditable(false);
        txtName.setEditable(false);
        txtSex.setEditable(false);
        txtAge.setEditable(false);
        txtDepartment.setEditable(false);
        txtClass.setEditable(false);
        txtTelephone.setEditable(false);

        btnTop = new JButton("第一条[T]");
        btnPrevious = new JButton("上一条[P]");
        btnNext = new JButton("下一条[N]");
        btnBottom = new JButton("最后一条[B]");
        btnExit = new JButton("退出[X]");
        btnTop.setMnemonic(KeyEvent.VK_T);
        btnPrevious.setMnemonic(KeyEvent.VK_P);
        btnNext.setMnemonic(KeyEvent.VK_N);
        btnBottom.setMnemonic(KeyEvent.VK_B);
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.setLayout(new BorderLayout());
        panel.add(pnlCenter, BorderLayout.CENTER);
        panel.add(pnlSouth, BorderLayout.SOUTH);
        pnlCenter.setLayout(new GridLayout(7, 1));

        pnlCenter.add(pnlRow1);
        pnlCenter.add(pnlRow2);
        pnlCenter.add(pnlRow3);
        pnlCenter.add(pnlRow4);
        pnlCenter.add(pnlRow5);
        pnlCenter.add(pnlRow6);
        pnlCenter.add(pnlRow7);

        pnlRow1.add(lblId);
        pnlRow1.add(txtId);
        pnlRow2.add(lblName);
        pnlRow2.add(txtName);
        pnlRow3.add(lblSex);
        pnlRow3.add(txtSex);
        pnlRow4.add(lblAge);
        pnlRow4.add(txtAge);
        pnlRow5.add(lblDepartment);
        pnlRow5.add(txtDepartment);
        pnlRow6.add(lblClass);
        pnlRow6.add(txtClass);
        pnlRow7.add(lblTelephone);
        pnlRow7.add(txtTelephone);

        pnlSouth.add(btnTop);
        pnlSouth.add(btnPrevious);
        pnlSouth.add(btnNext);
        pnlSouth.add(btnBottom);
        pnlSouth.add(btnExit);

        setSize(500, 300);
        setResizable(false);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        studentService = new StudentServiceImpl();
        students = studentService.findAllStudents();
        if (students.size() > 0) {
            currentRow = 1;
            setTitle("浏览学生表记录" + " && 当前记录:" + currentRow);
            fillFrameData(currentRow);
        } else {
            JOptionPane.showMessageDialog(null, "表中没有记录!", "浏览学生表记录", JOptionPane.ERROR_MESSAGE);
            btnTop.setEnabled(false);
            btnPrevious.setEnabled(false);
            btnNext.setEnabled(false);
            btnBottom.setEnabled(false);
        }

        btnTop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentRow = 1;
                fillFrameData(currentRow);
            }
        });

        btnPrevious.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (currentRow > 1) {
                    currentRow--;
                    fillFrameData(currentRow);
                } else {
                    JOptionPane.showMessageDialog(null, "已到第一条记录!", "浏览学生表记录", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        btnNext.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (currentRow < students.size()) {
                    currentRow++;
                    fillFrameData(currentRow);
                } else {
                    JOptionPane.showMessageDialog(null, "已到最后一条记录!", "浏览学生表记录", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        btnBottom.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentRow = students.size();
                fillFrameData(currentRow);
            }
        });

        btnExit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
    }


    private void fillFrameData(int currentRow) {
        if (currentRow > 0) {
            setTitle("浏览学生表记录" + " && 当前记录:" + currentRow);
            txtId.setText(students.get(currentRow - 1).getId());
            txtName.setText(students.get(currentRow - 1).getName());
            txtSex.setText(students.get(currentRow - 1).getSex());
            txtAge.setText(students.get(currentRow - 1).getAge() + "");
            txtDepartment.setText(students.get(currentRow - 1).getDepartment());
            txtClass.setText(students.get(currentRow - 1).getClazz());
            txtTelephone.setText(students.get(currentRow - 1).getTelephone());
        }
    }

    public static void main(String[] args) {
        new BrowseStudentsFrame("");
    }
}

  • 运行程序,查看结果

9、创建按学号删除学生窗口DeleteStudentByIdFrame

  • 在net.sxx.student.gui包里创建按学号删除学生窗口DeleteStudentByIdFrame
    在这里插入图片描述
  • 运行程序,查看效果
    请添加图片描述

10、创建按班级删除学生窗口DeleteStudentsByClassFrame

net.sxx.student.gui包里创建按班级删除学生窗口DeleteStudentsByClassFrame

package net.sxx.student.gui;

import net.sxx.student.bean.Student;
import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class DeleteStudentsByClassFrame extends JFrame {
    private JLabel lblInputClass;
    private JTextField txtClass;

    private JPanel panel;
    private JPanel pnlSouth;
    private JPanel pnlCenter;
    private JPanel pnlNorth;

    private JButton btnQuery;
    private JButton btnBrowseAll;
    private JButton btnDelete;
    private JButton btnExit;

    private Vector rows;
    private Vector<String> colHead;
    private JTable table;
    private JScrollPane scroller;
    private int currentRow;
    private List<Student> students;
    private StudentService studentService;

    public DeleteStudentsByClassFrame(String title) {
        super(title);
        intiGUI();
    }

    private void intiGUI() {
        panel = (JPanel) getContentPane();
        pnlNorth = new JPanel();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        rows = new Vector();
        colHead = new Vector();

        lblInputClass = new JLabel("输入班级:");
        txtClass = new JTextField(10);
        txtClass.setHorizontalAlignment(JTextField.CENTER);
        btnQuery = new JButton("查询[Q]");
        btnQuery.setMnemonic(KeyEvent.VK_Q);
        btnBrowseAll = new JButton("显示全部记录[A]");
        btnBrowseAll.setMnemonic(KeyEvent.VK_A);
        btnDelete = new JButton("删除查询的记录[D]");
        btnDelete.setEnabled(false);
        btnDelete.setMnemonic(KeyEvent.VK_D);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.add(pnlSouth, BorderLayout.SOUTH);
        panel.add(pnlCenter, BorderLayout.CENTER);
        panel.add(pnlNorth, BorderLayout.NORTH);

        pnlNorth.add(lblInputClass);
        pnlNorth.add(txtClass);
        pnlNorth.add(btnQuery);
        pnlNorth.add(btnBrowseAll);
        pnlSouth.setLayout(new FlowLayout(FlowLayout.RIGHT));
        pnlSouth.add(btnDelete);
        pnlSouth.add(btnExit);
        pnlCenter.setLayout(new BorderLayout());

        TitledBorder tb = new TitledBorder("查询结果");
        pnlCenter.setBorder(tb);

        studentService = new StudentServiceImpl();
        students = studentService.findAllStudents();
        fillTableData();

        setSize(600, 350);
        setResizable(false);
        setLocationRelativeTo(null);
        setTitle("按班级删除学生记录");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });

        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!rows.isEmpty()) {
                    long choice = JOptionPane.showConfirmDialog(null, "是否要删除记录?");
                    if (choice == JOptionPane.OK_OPTION) {
                        String clazz = txtClass.getText().trim();
                        int count = studentService.deleteStudentsByClass(clazz);
                        if (count > 0) {
                            JOptionPane.showMessageDialog(null, "记录删除成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
                            students = studentService.findAllStudents();
                            txtClass.setText("");
                            fillTableData();
                            btnDelete.setEnabled(false);
                        } else {
                            JOptionPane.showMessageDialog(null, "记录删除失败!", "警告", JOptionPane.WARNING_MESSAGE);
                        }
                    }
                }
            }
        });

        btnQuery.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                doQuery();
            }
        });

        btnBrowseAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                students = studentService.findAllStudents();
                fillTableData();
                btnDelete.setEnabled(false);
            }
        });

        txtClass.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    doQuery();
                }
            }
        });

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = table.rowAtPoint(e.getPoint());
                if (row <= table.getRowCount()) {
                    table.setRowSelectionInterval(row, row);
                    txtClass.setText(table.getValueAt(row, 5).toString());
                }
            }
        });
    }

    private void doQuery() {
        String clazz = txtClass.getText().trim();
        if (!clazz.equals("")) {
            students = studentService.findStudentsByClass(clazz);
            if (students.size() > 0) {
                btnDelete.setEnabled(true);
            }
            fillTableData();
        } else {
            JOptionPane.showMessageDialog(this, "请输入待查班级!", "警告", JOptionPane.WARNING_MESSAGE);
            txtClass.requestFocus();
        }
    }

    private void fillTableData() {
        colHead.clear();
        colHead.add("学号");
        colHead.add("姓名");
        colHead.add("性别");
        colHead.add("年龄");
        colHead.add("系部");
        colHead.add("班级");
        colHead.add("电话");

        rows.clear();
        for (Student student : students) {
            Vector<String> currentRow = new Vector<String>();
            currentRow.addElement(student.getId());
            currentRow.addElement(student.getName());
            currentRow.addElement(student.getSex());
            currentRow.addElement(student.getAge() + "");
            currentRow.addElement(student.getDepartment());
            currentRow.addElement(student.getClazz());
            currentRow.addElement(student.getTelephone());
            rows.add(currentRow);
        }

        table = new JTable(rows, colHead);

        scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pnlCenter.add(scroller, BorderLayout.CENTER);
        repaint();

        if (rows.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有符合条件的记录!", "错误提示", JOptionPane.WARNING_MESSAGE);
            txtClass.setText("");
        } else {
            scroller.getVerticalScrollBar().setValue(0);
        }
    }

    public static void main(String[] args) {
        new DeleteStudentsByClassFrame("");
    }
}


  • 运行程序,查看效果
    请添加图片描述

11、创建按系部删除学生窗口DeleteStudentsByDepartmentFrame

  • net.sxx.student.gui包里创建按系部删除学生窗口DeleteStudentsByDepartmentFrame
    在这里插入图片描述
package net.sxx.student.gui;

import net.sxx.student.bean.Student;
import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class DeleteStudentsByDepartmentFrame extends JFrame {
    private JLabel lblInputDepartment;
    private JTextField txtDepartment;

    private JPanel panel;
    private JPanel pnlSouth;
    private JPanel pnlCenter;
    private JPanel pnlNorth;

    private JButton btnQuery;
    private JButton btnBrowseAll;
    private JButton btnDelete;
    private JButton btnExit;

    private Vector rows;
    private Vector<String> colHead;
    private JTable table;
    private JScrollPane scroller;

    private int currentRow;
    private List<Student> students;
    private StudentService studentService;

    public DeleteStudentsByDepartmentFrame(String title) {
        super(title);
        intiGUI();
    }

    private void intiGUI() {
        panel = (JPanel) getContentPane();
        pnlNorth = new JPanel();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        rows = new Vector();
        colHead = new Vector();

        lblInputDepartment = new JLabel("输入系部:");
        txtDepartment = new JTextField(10);
        txtDepartment.setHorizontalAlignment(JTextField.CENTER);
        btnQuery = new JButton("查询[Q]");
        btnQuery.setMnemonic(KeyEvent.VK_Q);
        btnBrowseAll = new JButton("显示全部记录[A]");
        btnBrowseAll.setMnemonic(KeyEvent.VK_A);
        btnDelete = new JButton("删除查询的记录[D]");
        btnDelete.setEnabled(false);// 删除按钮不可用
        btnDelete.setMnemonic(KeyEvent.VK_D);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.add(pnlSouth, BorderLayout.SOUTH);
        panel.add(pnlCenter, BorderLayout.CENTER);
        panel.add(pnlNorth, BorderLayout.NORTH);

        pnlNorth.add(lblInputDepartment);
        pnlNorth.add(txtDepartment);
        pnlNorth.add(btnQuery);
        pnlNorth.add(btnBrowseAll);
        pnlSouth.setLayout(new FlowLayout(FlowLayout.RIGHT));
        pnlSouth.add(btnDelete);
        pnlSouth.add(btnExit);
        pnlCenter.setLayout(new BorderLayout());

        TitledBorder tb = new TitledBorder("查询结果");
        pnlCenter.setBorder(tb);

        studentService = new StudentServiceImpl();
        students = studentService.findAllStudents();
        fillTableData();

        setSize(600, 350);
        setResizable(false);
        setLocationRelativeTo(null);
        setTitle("按系部删除学生记录");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });

        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!rows.isEmpty()) {
                    long choice = JOptionPane.showConfirmDialog(null, "是否要删除记录?");
                    if (choice == JOptionPane.OK_OPTION) {
                        String department = txtDepartment.getText().trim();
                        int count = studentService.deleteStudentsByDepartment(department);
                        if (count > 0) {
                            JOptionPane.showMessageDialog(null, "记录删除成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
                            students = studentService.findAllStudents();
                            txtDepartment.setText("");
                            fillTableData();
                            btnDelete.setEnabled(false);
                        } else {
                            JOptionPane.showMessageDialog(null, "记录删除失败!", "警告", JOptionPane.WARNING_MESSAGE);
                        }
                    }
                }
            }
        });

        btnQuery.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                doQuery();
            }
        });

        btnBrowseAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                students = studentService.findAllStudents();
                fillTableData();
                btnDelete.setEnabled(false);
            }
        });

        txtDepartment.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    doQuery();
                }
            }
        });

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = table.rowAtPoint(e.getPoint());
                table.setRowSelectionInterval(row, row);
                txtDepartment.setText(table.getValueAt(row, 4).toString());
            }
        });
    }

    private void doQuery() {
        String department = txtDepartment.getText().trim();
        if (!department.equals("")) {
            students = studentService.findStudentsByDepartment(department);
            if (students.size() > 0) {
                btnDelete.setEnabled(true);
            }
            fillTableData();
        } else {
            JOptionPane.showMessageDialog(this, "请输入待查系部!", "警告", JOptionPane.WARNING_MESSAGE);
            txtDepartment.requestFocus();
        }
    }

    private void fillTableData() {
        colHead.clear();
        colHead.add("学号");
        colHead.add("姓名");
        colHead.add("性别");
        colHead.add("年龄");
        colHead.add("系部");
        colHead.add("班级");
        colHead.add("电话");
        rows.clear();
        for (Student student : students) {
            Vector<String> currentRow = new Vector<String>();
            currentRow.addElement(student.getId());
            currentRow.addElement(student.getName());
            currentRow.addElement(student.getSex());
            currentRow.addElement(student.getAge() + "");
            currentRow.addElement(student.getDepartment());
            currentRow.addElement(student.getClazz());
            currentRow.addElement(student.getTelephone());
            rows.add(currentRow);
        }
        table = new JTable(rows, colHead);
        scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pnlCenter.add(scroller, BorderLayout.CENTER);
        repaint();
        if (rows.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有符合条件的记录!", "错误提示", JOptionPane.WARNING_MESSAGE);
            txtDepartment.setText("");
        } else {
            scroller.getVerticalScrollBar().setValue(0);
        }
    }

    public static void main(String[] args) {
        new DeleteStudentsByDepartmentFrame("");
    }
}

  • 运行程序,查看效果
    请添加图片描述

12、创建按学号查询学生窗口FindStudentByIdFrame

  • net.sxx.student.gui包里创建按学号查询学生窗口FindStudentByIdFrame
    在这里插入图片描述
package net.sxx.student.gui;

import net.sxx.student.bean.Student;
import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.util.List;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class FindStudentByIdFrame extends JFrame {
    private JLabel lblInputId;
    private JTextField txtId;

    private JPanel panel;
    private JPanel pnlSouth;
    private JPanel pnlCenter;
    private JPanel pnlNorth;

    private JButton btnQuery;
    private JButton btnBrowseAll;
    private JButton btnPrint;
    private JButton btnExit;

    private JScrollPane scroller;

    private Vector rows;
    private Vector<String> colHead;
    private JTable table;
    private List<Student> students;
    private StudentService studentService;

    public FindStudentByIdFrame(String title) {
        super(title);
        intiGUI();
    }

    private void intiGUI() {
        panel = (JPanel) getContentPane();
        pnlNorth = new JPanel();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        rows = new Vector();
        colHead = new Vector();

        lblInputId = new JLabel("输入学号:");
        txtId = new JTextField(10);
        txtId.setHorizontalAlignment(JTextField.CENTER);
        btnQuery = new JButton("查询[Q]");
        btnQuery.setMnemonic(KeyEvent.VK_Q);
        btnBrowseAll = new JButton("显示全部记录[A]");
        btnBrowseAll.setMnemonic(KeyEvent.VK_A);
        btnPrint = new JButton("打印[P]");
        btnPrint.setMnemonic(KeyEvent.VK_D);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.add(pnlSouth, BorderLayout.SOUTH);
        panel.add(pnlCenter, BorderLayout.CENTER);
        panel.add(pnlNorth, BorderLayout.NORTH);

        pnlNorth.add(lblInputId);
        pnlNorth.add(txtId);
        pnlNorth.add(btnQuery);
        pnlNorth.add(btnBrowseAll);
        pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER, 120, 3));
        pnlSouth.add(btnPrint,BorderLayout.WEST);
        pnlSouth.add(btnExit,BorderLayout.EAST);
        pnlCenter.setLayout(new BorderLayout());

        TitledBorder tb = new TitledBorder("查询结果");
        pnlCenter.setBorder(tb);

        studentService = new StudentServiceImpl();
        students = studentService.findAllStudents();
        fillTableData();

        setSize(600, 350);
        setResizable(false);
        setLocationRelativeTo(null);
        setTitle("按学号查询学生记录");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });

        btnPrint.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    table.print();
                } catch (PrinterException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        btnQuery.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                doQuery();
            }
        });

        btnBrowseAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                students = studentService.findAllStudents();
                fillTableData();
                btnPrint.setEnabled(false);
            }
        });

        txtId.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    doQuery();
                }
            }
        });

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = table.rowAtPoint(e.getPoint());
                table.setRowSelectionInterval(row, row);
                txtId.setText(table.getValueAt(row, 0).toString());
            }
        });
    }

    private void doQuery() {
        String id = txtId.getText().trim();
        if (!id.equals("")) {
            students.clear();
            Student student = studentService.findStudentById(id);
            if (student != null) {
                students.add(student);
            }
            fillTableData();
        } else {
            JOptionPane.showMessageDialog(this, "请输入待查学生学号!", "警告", JOptionPane.WARNING_MESSAGE);
            txtId.requestFocus();
        }
    }

    private void fillTableData() {
        colHead.clear();
        colHead.add("学号");
        colHead.add("姓名");
        colHead.add("性别");
        colHead.add("年龄");
        colHead.add("系部");
        colHead.add("班级");
        colHead.add("电话");

        rows.clear();
        for (Student student : students) {
            Vector<String> currentRow = new Vector<String>();
            currentRow.addElement(student.getId());
            currentRow.addElement(student.getName());
            currentRow.addElement(student.getSex());
            currentRow.addElement(student.getAge() + "");
            currentRow.addElement(student.getDepartment());
            currentRow.addElement(student.getClazz());
            currentRow.addElement(student.getTelephone());
            rows.add(currentRow);
        }

        table = new JTable(rows, colHead);

        scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pnlCenter.add(scroller, BorderLayout.CENTER);
        repaint();

        if (rows.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有符合条件的记录!", "错误提示", JOptionPane.WARNING_MESSAGE);
            txtId.setText("");
        } else {
            scroller.getVerticalScrollBar().setValue(0);
        }
    }

    public static void main(String[] args) {
        new FindStudentByIdFrame("");
    }
}


  • 运行程序,查看效果
    请添加图片描述

13、创建按姓名查询学生窗口FindStudentsByNameFrame

  • 在net.sxx.student.gui包里创建按姓名查询学生窗口FindStudentsByNameFrame

在这里插入图片描述

package net.sxx.student.gui;

import net.sxx.student.bean.Student;
import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.util.List;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class FindStudentsByNameFrame extends JFrame {
    private JLabel lblInputName;
    private JTextField txtName;

    private JPanel panel;
    private JPanel pnlSouth;
    private JPanel pnlCenter;
    private JPanel pnlNorth;

    private JButton btnQuery;
    private JButton btnBrowseAll;
    private JButton btnPrint;
    private JButton btnExit;

    private Vector rows;
    private Vector<String> colHead;

    private JTable table;
    private JScrollPane scroller;
    private int currentRow;
    private List<Student> students;
    private StudentService studentService;

    public FindStudentsByNameFrame(String title) {
        super(title);
        intiGUI();
    }

    private void intiGUI() {
        panel = (JPanel) getContentPane();
        pnlNorth = new JPanel();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        rows = new Vector();
        colHead = new Vector();

        lblInputName = new JLabel("输入姓名:");
        txtName = new JTextField(10);
        txtName.setHorizontalAlignment(JTextField.CENTER);
        btnQuery = new JButton("查询[Q]");
        btnQuery.setMnemonic(KeyEvent.VK_Q);
        btnBrowseAll = new JButton("显示全部记录[A]");
        btnBrowseAll.setMnemonic(KeyEvent.VK_A);
        btnPrint = new JButton("打印[P]");
        btnPrint.setMnemonic(KeyEvent.VK_D);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.add(pnlSouth, BorderLayout.SOUTH);
        panel.add(pnlCenter, BorderLayout.CENTER);
        panel.add(pnlNorth, BorderLayout.NORTH);

        pnlNorth.add(lblInputName);
        pnlNorth.add(txtName);
        pnlNorth.add(btnQuery);
        pnlNorth.add(btnBrowseAll);
        pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER, 120, 3));
        pnlSouth.add(btnPrint,BorderLayout.WEST);
        pnlSouth.add(btnExit,BorderLayout.EAST);
        pnlCenter.setLayout(new BorderLayout());

        TitledBorder tb = new TitledBorder("查询结果");
        pnlCenter.setBorder(tb);

        studentService = new StudentServiceImpl();
        students = studentService.findAllStudents();
        fillTableData();

        setSize(600, 350);
        setResizable(false);
        setLocationRelativeTo(null);
        setTitle("按姓名查询学生记录");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });

        btnPrint.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    table.print();
                } catch (PrinterException e1) {
                    e1.printStackTrace();
                }
            }
        });

        btnQuery.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                doQuery();
            }
        });

        btnBrowseAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                students = studentService.findAllStudents();
                fillTableData();
            }
        });

        txtName.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    doQuery();
                }
            }
        });

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = table.rowAtPoint(e.getPoint());
                table.setRowSelectionInterval(row, row);
                txtName.setText(table.getValueAt(row, 1).toString());
            }
        });
    }

    private void doQuery() {
        String name = txtName.getText().trim();
        if (!name.equals("")) {
            students = studentService.findStudentsByName(name);
            fillTableData();
        } else {
            JOptionPane.showMessageDialog(this, "请输入待查学生姓名!", "警告", JOptionPane.WARNING_MESSAGE);
            txtName.requestFocus();
        }
    }

    private void fillTableData() {
        colHead.clear();
        colHead.add("姓名");
        colHead.add("姓名");
        colHead.add("性别");
        colHead.add("年龄");
        colHead.add("系部");
        colHead.add("班级");
        colHead.add("电话");
        rows.clear();
        for (Student student : students) {
            Vector<String> currentRow = new Vector<String>();
            currentRow.addElement(student.getId());
            currentRow.addElement(student.getName());
            currentRow.addElement(student.getSex());
            currentRow.addElement(student.getAge() + "");
            currentRow.addElement(student.getDepartment());
            currentRow.addElement(student.getClazz());
            currentRow.addElement(student.getTelephone());
            rows.add(currentRow);
        }

        table = new JTable(rows, colHead);
        scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pnlCenter.add(scroller, BorderLayout.CENTER);
        repaint();
        if (rows.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有符合条件的记录!", "错误提示", JOptionPane.WARNING_MESSAGE);
            txtName.setText("");
        } else {
            scroller.getVerticalScrollBar().setValue(0);
        }
    }

    public static void main(String[] args) {
        new FindStudentsByNameFrame("");
    }
}

  • 运行成功,查看效果图
    请添加图片描述

14、创建按班级查询学生窗口FindStudentsByClassFrame

  • 在net.sxx.student.gui包里创建按班级查询学生窗口FindStudentsByClassFrame
    在这里插入图片描述
package net.sxx.student.gui;

import net.sxx.student.bean.Student;
import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.util.List;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class FindStudentsByClassFrame extends JFrame {
    private JLabel lblInputClass;
    private JTextField txtClass;

    private JPanel panel;
    private JPanel pnlSouth;
    private JPanel pnlCenter;
    private JPanel pnlNorth;

    private JButton btnQuery;
    private JButton btnBrowseAll;
    private JButton btnPrint;
    private JButton btnExit;

    private Vector rows;
    private Vector<String> colHead;

    private JTable table;
    private JScrollPane scroller;
    private int currentRow;
    private List<Student> students;
    private StudentService studentService;

    public FindStudentsByClassFrame(String title) {
        super(title);
        intiGUI();
    }

    private void intiGUI() {
        panel = (JPanel) getContentPane();
        pnlNorth = new JPanel();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        rows = new Vector();
        colHead = new Vector();

        lblInputClass = new JLabel("输入班级:");
        txtClass = new JTextField(10);
        txtClass.setHorizontalAlignment(JTextField.CENTER);
        btnQuery = new JButton("查询[Q]");
        btnQuery.setMnemonic(KeyEvent.VK_Q);
        btnBrowseAll = new JButton("显示全部记录[A]");
        btnBrowseAll.setMnemonic(KeyEvent.VK_A);
        btnPrint = new JButton("打印[P]");
        btnPrint.setMnemonic(KeyEvent.VK_D);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.add(pnlSouth, BorderLayout.SOUTH);
        panel.add(pnlCenter, BorderLayout.CENTER);
        panel.add(pnlNorth, BorderLayout.NORTH);

        pnlNorth.add(lblInputClass);
        pnlNorth.add(txtClass);
        pnlNorth.add(btnQuery);
        pnlNorth.add(btnBrowseAll);
        pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER, 120, 3));
        pnlSouth.add(btnPrint,BorderLayout.WEST);
        pnlSouth.add(btnExit,BorderLayout.EAST);
        pnlCenter.setLayout(new BorderLayout());

        TitledBorder tb = new TitledBorder("查询结果");
        pnlCenter.setBorder(tb);

        studentService = new StudentServiceImpl();
        students = studentService.findAllStudents();
        fillTableData();

        setSize(600, 350);
        setResizable(false);
        setLocationRelativeTo(null);
        setTitle("按姓名查询学生记录");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });
        btnPrint.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    table.print();
                } catch (PrinterException e1) {
                    e1.printStackTrace();
                }
            }
        });

        btnQuery.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                doQuery();
            }
        });

        btnBrowseAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                students = studentService.findAllStudents();
                fillTableData();
            }
        });
        txtClass.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    doQuery();
                }
            }
        });

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = table.rowAtPoint(e.getPoint());
                table.setRowSelectionInterval(row, row);
                txtClass.setText(table.getValueAt(row, 5).toString());
            }
        });
    }

    private void doQuery() {
        String clazz = txtClass.getText().trim();
        if (!clazz.equals("")) {
            students = studentService.findStudentsByClass(clazz);
            fillTableData();
        } else {
            JOptionPane.showMessageDialog(this, "请输入待查班级!", "警告", JOptionPane.WARNING_MESSAGE);
            txtClass.requestFocus();
        }
    }

    private void fillTableData() {
        colHead.clear();
        colHead.add("班级");
        colHead.add("班级");
        colHead.add("性别");
        colHead.add("年龄");
        colHead.add("系部");
        colHead.add("班级");
        colHead.add("电话");
        rows.clear();
        for (Student student : students) {
            Vector<String> currentRow = new Vector<String>();
            currentRow.addElement(student.getId());
            currentRow.addElement(student.getName());
            currentRow.addElement(student.getSex());
            currentRow.addElement(student.getAge() + "");
            currentRow.addElement(student.getDepartment());
            currentRow.addElement(student.getClazz());
            currentRow.addElement(student.getTelephone());
            rows.add(currentRow);
        }
        table = new JTable(rows, colHead);
        scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pnlCenter.add(scroller, BorderLayout.CENTER);
        repaint();
        if (rows.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有符合条件的记录!", "错误提示", JOptionPane.WARNING_MESSAGE);
            txtClass.setText("");
        } else {
            scroller.getVerticalScrollBar().setValue(0);
        }
    }

    public static void main(String[] args) {
        new FindStudentsByClassFrame("");
    }
}


  • 运行程序,查看效果
    请添加图片描述

15、创建按系部查询学生窗口FindStudentsByDepartmentFrame

  • net.sxx.student.gui包里创建按系部查询学生窗口FindStudentsByDepartmentFrame
package net.sxx.student.gui;

import net.sxx.student.bean.Student;
import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.util.List;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class FindStudentsByDepartmentFrame extends JFrame {
    private JLabel lblInputDepartment;
    private JTextField txtDepartment;

    private JPanel panel;
    private JPanel pnlSouth;
    private JPanel pnlCenter;
    private JPanel pnlNorth;

    private JButton btnQuery;
    private JButton btnBrowseAll;
    private JButton btnPrint;
    private JButton btnExit;

    private Vector rows;
    private Vector<String> colHead;

    private JTable table;
    private JScrollPane scroller;

    private int currentRow;
    private List<Student> students;
    private StudentService studentService;

    public FindStudentsByDepartmentFrame(String title) {
        super(title);
        intiGUI();
    }

    private void intiGUI() {
        panel = (JPanel) getContentPane();
        pnlNorth = new JPanel();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        rows = new Vector();
        colHead = new Vector();

        lblInputDepartment = new JLabel("输入系部:");
        txtDepartment = new JTextField(10);
        txtDepartment.setHorizontalAlignment(JTextField.CENTER);
        btnQuery = new JButton("查询[Q]");
        btnQuery.setMnemonic(KeyEvent.VK_Q);
        btnBrowseAll = new JButton("显示全部记录[A]");
        btnBrowseAll.setMnemonic(KeyEvent.VK_A);
        btnPrint = new JButton("打印[P]");
        btnPrint.setMnemonic(KeyEvent.VK_D);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.add(pnlSouth, BorderLayout.SOUTH);
        panel.add(pnlCenter, BorderLayout.CENTER);
        panel.add(pnlNorth, BorderLayout.NORTH);

        pnlNorth.add(lblInputDepartment);
        pnlNorth.add(txtDepartment);
        pnlNorth.add(btnQuery);
        pnlNorth.add(btnBrowseAll);
        pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER, 120, 3));
        pnlSouth.add(btnPrint,BorderLayout.WEST);
        pnlSouth.add(btnExit,BorderLayout.EAST);
        pnlCenter.setLayout(new BorderLayout());

        TitledBorder tb = new TitledBorder("查询结果");
        pnlCenter.setBorder(tb);
        studentService = new StudentServiceImpl();
        students = studentService.findAllStudents();

        fillTableData();
        setSize(600, 350);
        setResizable(false);
        setLocationRelativeTo(null);
        setTitle("按系部查询学生记录");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });

        btnPrint.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    table.print();
                } catch (PrinterException e1) {
                    e1.printStackTrace();
                }
            }
        });

        btnQuery.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                doQuery();
            }
        });

        btnBrowseAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                students = studentService.findAllStudents();
                fillTableData();
            }
        });

        txtDepartment.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    doQuery();
                }
            }
        });

        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = table.rowAtPoint(e.getPoint());
                table.setRowSelectionInterval(row, row);
                txtDepartment.setText(table.getValueAt(row, 4).toString());
            }
        });
    }

    private void doQuery() {
        String department = txtDepartment.getText().trim();
        if (!department.equals("")) {
            students = studentService.findStudentsByDepartment(department);
            fillTableData();
        } else {
            JOptionPane.showMessageDialog(this, "请输入待查系部!", "警告", JOptionPane.WARNING_MESSAGE);
            txtDepartment.requestFocus();
        }
    }

    private void fillTableData() {
        colHead.clear();
        colHead.add("系部");
        colHead.add("系部");
        colHead.add("性别");
        colHead.add("年龄");
        colHead.add("系部");
        colHead.add("系部");
        colHead.add("电话");
        rows.clear();
        for (Student student : students) {
            Vector<String> currentRow = new Vector<String>();
            currentRow.addElement(student.getId());
            currentRow.addElement(student.getName());
            currentRow.addElement(student.getSex());
            currentRow.addElement(student.getAge() + "");
            currentRow.addElement(student.getDepartment());
            currentRow.addElement(student.getClazz());
            currentRow.addElement(student.getTelephone());
            rows.add(currentRow);
        }
        table = new JTable(rows, colHead);
        scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pnlCenter.add(scroller, BorderLayout.CENTER);
        repaint();
        if (rows.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有符合条件的记录!", "错误提示", JOptionPane.WARNING_MESSAGE);
            txtDepartment.setText("");
        } else {
            scroller.getVerticalScrollBar().setValue(0);
        }
    }

    public static void main(String[] args) {
        new FindStudentsByDepartmentFrame("");
    }
}

  • 运行程序,查看效果
    请添加图片描述

16、创建按性别统计人数窗口CountStudentsBySexFrame

  • 在net.sxx.student.gui包里创建性别统计人数窗口CountStudentsBySexFrame
    在这里插入图片描述
package net.sxx.student.gui;

import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.print.PrinterException;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class CountStudentsBySexFrame extends JFrame {
    private JPanel panel;
    private JPanel pnlSouth;
    private JPanel pnlCenter;

    private JButton btnPrint;
    private JButton btnExit;

    private JScrollPane scroller;

    private Vector rows;
    private Vector<String> colHead;
    private JTable table;
    private StudentService studentService;

    public CountStudentsBySexFrame(String title) {
        super(title);
        initGUI();
    }

    private void initGUI() {
        panel = (JPanel) getContentPane();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        rows = new Vector();
        colHead = new Vector();

        btnPrint = new JButton("打印[P]");
        btnPrint.setMnemonic(KeyEvent.VK_P);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.add(pnlSouth, BorderLayout.SOUTH);
        panel.add(pnlCenter, BorderLayout.CENTER);

        pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER, 50, 3));
        pnlSouth.add(btnPrint,BorderLayout.WEST);
        pnlSouth.add(btnExit,BorderLayout.EAST);
        pnlCenter.setLayout(new BorderLayout());

        TitledBorder tb = new TitledBorder("统计结果");
        pnlCenter.setBorder(tb);

        studentService = new StudentServiceImpl();
        rows = studentService.findRowsBySex();
        colHead.add("性别");
        colHead.add("人数");

        table = new JTable(rows, colHead);
        scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pnlCenter.add(scroller, BorderLayout.CENTER);

        repaint();

        if (rows.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有记录!", "错误提示", JOptionPane.WARNING_MESSAGE);
        }

        setSize(300, 200);
        setResizable(false);
        setLocationRelativeTo(null);
        setTitle("按性别统计学生人数");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                dispose();
            }
        });

        btnPrint.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    table.print();
                } catch (PrinterException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
    }

    public static void main(String[] args) {
        new CountStudentsBySexFrame("");
    }
}


  • 运行程序,查看结果
    请添加图片描述

17、创建按班级统计人数窗口CountStudentsByClassFrame

  • net.sxx.student.gui包里创建按班级统计人数窗口CountStudentsByClassFrame
    在这里插入图片描述
package net.sxx.student.gui;

import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.print.PrinterException;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class CountStudentsByClassFrame extends JFrame {
    private JPanel panel;
    private JPanel pnlSouth;
    private JPanel pnlCenter;

    private JButton btnPrint;
    private JButton btnExit;

    private Vector rows;
    private Vector<String> colHead;

    private JTable table;
    private JScrollPane scroller;
    private StudentService studentService;

    public CountStudentsByClassFrame(String title) {
        super(title);
        initGUI();
    }

    private void initGUI() {
        panel = (JPanel) getContentPane();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        rows = new Vector();
        colHead = new Vector();

        btnPrint = new JButton("打印[P]");
        btnPrint.setMnemonic(KeyEvent.VK_P);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.add(pnlSouth, BorderLayout.SOUTH);
        panel.add(pnlCenter, BorderLayout.CENTER);

        pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER,50,3));
        pnlSouth.add(btnPrint);
        pnlSouth.add(btnExit);
        pnlCenter.setLayout(new BorderLayout());

        TitledBorder tb = new TitledBorder("统计结果");
        pnlCenter.setBorder(tb);
        studentService = new StudentServiceImpl();
        rows = studentService.findRowsByClass();
        colHead.add("班级");
        colHead.add("人数");
        table = new JTable(rows, colHead);
        scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pnlCenter.add(scroller, BorderLayout.CENTER);
        repaint();
        if (rows.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有记录!", "错误提示", JOptionPane.WARNING_MESSAGE);
        }

        setSize(300, 200);
        setResizable(false);
        setLocationRelativeTo(null);
        setTitle("按班级统计学生人数");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                dispose();
            }
        });

        btnPrint.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    table.print();
                } catch (PrinterException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }

    public static void main(String[] args) {
        new CountStudentsByClassFrame("");
    }
}

  • 运行程序,查看效果
    请添加图片描述

18、创建按系部统计人数窗口CountStudentsByDepartmentFrame

  • net.sxx.student.gui包里创建按系部统计人数窗口CountStudentsByDepartmentFrame
    在这里插入图片描述
package net.sxx.student.gui;

import net.sxx.student.service.StudentService;
import net.sxx.student.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.print.PrinterException;
import java.util.Vector;

/**
 * 功能:
 * 作者:孙希霞
 * 日期:2023年06月17日
 */
public class CountStudentsByDepartmentFrame extends JFrame {
    private JPanel panel;
    private JPanel pnlSouth;
    private JPanel pnlCenter;

    private JButton btnPrint;
    private JButton btnExit;

    private Vector rows;
    private Vector<String> colHead;

    private JTable table;
    private JScrollPane scroller;
    private StudentService studentService;

    public CountStudentsByDepartmentFrame(String title) {
        super(title);
        initGUI();
    }

    private void initGUI() {
        panel = (JPanel) getContentPane();
        pnlCenter = new JPanel();
        pnlSouth = new JPanel();

        rows = new Vector();
        colHead = new Vector();

        btnPrint = new JButton("打印[P]");
        btnPrint.setMnemonic(KeyEvent.VK_P);
        btnExit = new JButton("退出[X]");
        btnExit.setMnemonic(KeyEvent.VK_X);

        panel.add(pnlSouth, BorderLayout.SOUTH);
        panel.add(pnlCenter, BorderLayout.CENTER);

        pnlSouth.setLayout(new BorderLayout());
        pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER, 50, 3));
        pnlSouth.add(btnPrint,BorderLayout.WEST);
        pnlSouth.add(btnExit,BorderLayout.EAST);
        pnlCenter.setLayout(new BorderLayout());

        TitledBorder tb = new TitledBorder("统计结果");
        pnlCenter.setBorder(tb);

        studentService = new StudentServiceImpl();
        rows = studentService.findRowsByDepartment();
        colHead.add("系部");
        colHead.add("人数");

        table = new JTable(rows, colHead);
        scroller = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pnlCenter.add(scroller, BorderLayout.CENTER);

        repaint();

        if (rows.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有记录!", "错误提示", JOptionPane.WARNING_MESSAGE);
        }

        setSize(300, 200);
        setResizable(false);
        setLocationRelativeTo(null);
        setTitle("按系部统计学生人数");
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                dispose();
            }
        });

        btnPrint.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    table.print();
                } catch (PrinterException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }

    public static void main(String[] args) {
        new CountStudentsByDepartmentFrame("");
    }
}


  • 运行程序,查看效果
    请添加图片描述

19、创建设置状态栏信息窗口SetStatusBarFrame

  • net.sxx.student.gui包里创建设置状态栏信息窗口SetStatusBarFrame
    在这里插入图片描述

  • 程序会有处报错
    在这里插入图片描述

  • 等到MainFrame类里写好setStatusBar()方法之后,消除错误之后,才能测试该程序

20、修改主界面窗口MainFrame

  • 添加菜单系统及其事件处理
  • 添加主界面背景标签的图片
  • 设置主界面的状态栏信息
  • 运行程序,查看结果
    请添加图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值