项目概述
开发环境
IDEA 2023.2.2
MySQL8.0.33
JDK17
使用技术
JavaGUI + JDBC + Maven
项目详情
项目结构
base:创建实体类并实现Excel表格导出的基本功能
dao:实现对数据库的连接及增、删、改、查各种操作
system:实现各窗口的布局和样式
项目依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>ClassroomSystem</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
</dependencies>
</project>
//注:如果不使用Maven可以下载jar包进行导入项目也可以
mysql-connector-java.jar下载地址https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.27
Apache-poi.jarhttps://mvnrepository.com/artifact/org.apache.poi/poi/3.16
项目图片
项目代码
交互界面代码
1.登录页面
package system;
import dao.ActionDao;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LoginGUI extends JFrame implements ActionListener {
private JLabel loginText, usernameLabel, passwordLabel;
private JTextField usernameField, passwordField;
private JPanel northrPanel, inputPanel, usernamePanel, passwordPanel, southPanel;
private JButton loginButton, registerButton;
public LoginGUI() {
this.setTitle("教室后台管理系统");
this.setBounds(760, 340, 400, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLayout(new BorderLayout());
// 标题面板
this.usernamePanel = new JPanel();
this.passwordPanel = new JPanel();
this.northrPanel = new JPanel();
this.inputPanel = new JPanel(new GridLayout(2, 1));
this.loginText = new JLabel("登录");
this.loginText.setFont(new Font("楷体", Font.BOLD, 30));
this.usernameLabel = new JLabel("用户:");
this.passwordLabel = new JLabel("密码:");
// 用户名输入面板
this.usernameField = new JTextField("请输入用户名", 12);
this.usernamePanel.add(usernameLabel);
this.usernamePanel.add(usernameField);
// 密码输入面板
this.passwordField = new JTextField("请输入密码", 12);
this.passwordPanel.add(passwordLabel);
this.passwordPanel.add(passwordField);
// 输入信息面板
this.inputPanel.add(usernamePanel);
this.inputPanel.add(passwordPanel);
// 按钮面板
this.loginButton = new JButton("登录");
this.loginButton.addActionListener(this);
this.registerButton = new JButton("注册");
this.registerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
new RegisterGUI();
}
});
this.southPanel = new JPanel();
this.southPanel.add(loginButton);
this.southPanel.add(registerButton);
// 添加组件到窗口
this.northrPanel.add(loginText);
this.add(northrPanel, BorderLayout.NORTH);
this.add(inputPanel, BorderLayout.CENTER);
this.add(southPanel, BorderLayout.SOUTH);
// 设置窗口可见
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// 获取用户名和密码
String username = usernameField.getText();
String password = passwordField.getText();
// 调用数据访问对象的登录方法
ActionDao ActionDao = new ActionDao();
String loginResult = ActionDao.LoginDao(username, password);
System.out.println(loginResult);
// 判断登录结果
if(loginResult.equals("YES")) {
// 登录成功,关闭当前窗口,打开系统界面
this.setVisible(false);
new SystemGUI();
} else {
// 登录失败,打印提示信息
System.out.println("登录失败");
}
}
public static void main(String[] args) {
// 启动登录界面
new LoginGUI();
}
}
2.注册页面
package system;
import dao.ActionDao;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RegisterGUI extends JFrame {
private JPanel titlePanel, regiserPanel, usernamePanel, passwordPanel, passwordsPanel, buttonPanel;
private JLabel titleLabel, usernameLabel, passwordLabel, passwordsLabel;
private JTextField usernameField, passwordField, passwordsField;
private JButton registerButton, returnButton;
public RegisterGUI() {
this.setTitle("教室后台管理系统");
this.setBounds(760, 340, 400, 240);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLayout(new BorderLayout());
// 标题面板
this.titlePanel = new JPanel();
this.titleLabel = new JLabel("注册");
this.titleLabel.setFont(new Font("楷体", Font.BOLD, 30));
this.titlePanel.add(titleLabel);
// 注册信息面板
this.regiserPanel = new JPanel(new GridLayout(3, 1));
this.usernamePanel = new JPanel();
this.passwordPanel = new JPanel();
this.passwordsPanel = new JPanel();
this.usernameLabel = new JLabel("注册用户:");
this.passwordLabel = new JLabel("注册密码:");
this.passwordsLabel = new JLabel("确认密码:");
this.usernameField = new JTextField("请输入用户名", 12);
this.passwordField = new JTextField("请输入密码", 12);
this.passwordsField = new JTextField("请再次输入密码", 12);
this.usernamePanel.add(usernameLabel);
this.usernamePanel.add(usernameField);
this.passwordPanel.add(passwordLabel);
this.passwordPanel.add(passwordField);
this.passwordsPanel.add(passwordsLabel);
this.passwordsPanel.add(passwordsField);
this.regiserPanel.add(usernamePanel);
this.regiserPanel.add(passwordPanel);
this.regiserPanel.add(passwordsPanel);
// 按钮面板
this.buttonPanel = new JPanel();
this.registerButton = new JButton("注册");
this.registerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 调用数据访问对象的注册方法
ActionDao actionDao = new ActionDao();
String register = actionDao.RegisterDao(usernameField.getText(), passwordField.getText());
if(register.equals("YES")) {
System.out.println("注册成功");
}
}
});
this.returnButton = new JButton("返回");
this.returnButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 关闭当前窗口,打开登录界面
setVisible(false);
new LoginGUI();
}
});
this.buttonPanel.add(registerButton);
this.buttonPanel.add(returnButton);
// 添加组件到窗口
this.add(titlePanel, BorderLayout.NORTH);
this.add(regiserPanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
// 设置窗口可见
this.setVisible(true);
}
}
3.增删改查操作主页面
package system;
import base.ClassRoom;
import base.FileAction;
import dao.ActionDao;
import dao.ClassDao;
import dao.ClassDaoImp;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Vector;
public class SystemGUI extends JFrame {
private JPanel leftPanel, rightPanel, titlePanel, leftCellPanel, idPanel, namePanel, numberPanel, addressPanel, stylePanel, statePanel, userPanel, fileButtonPanel, actionPanel;
private JSplitPane splitPane;
private Integer row;
private JLabel titleLabel, fileLabel;
private JTextField idField, nameField, numberField, addressField, styleField, stateField, userField;
private JScrollPane tableScrollPane;
private DefaultTableModel tableModel;
private JTable classtable;
private JButton fileButton, addButton, deleteButton, updateButton;
private JComboBox<String> fileComboBox;
private String SelectAll[] = {".xls", ".csv"};
private String columnNames[] = {"教室序号", "教室编号", "可容纳数", "所在楼名", "教室类型", "使用状态", "使用人员"};
public SystemGUI() {
this.setTitle("教室后台管理系统");
this.setBounds(420, 315, 1040, 450);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
// 设置标题标签
this.titleLabel = new JLabel("教室信息汇总表");
this.titleLabel.setFont(new Font("华文隶书", Font.BOLD, 32));
// 创建表格模型并添加列名
this.tableModel = new DefaultTableModel();
this.tableModel.setColumnIdentifiers(columnNames);
// 从数据库中查询教室信息并添加到表格模型中
ClassDao dao = new ClassDaoImp();
List<ClassRoom> classRooms = dao.findAll();
for (ClassRoom classRoom : classRooms) {
Object[] rowData = {
classRoom.getId(),
classRoom.getName(),
classRoom.getNumber(),
classRoom.getAddress(),
classRoom.getStyle(),
classRoom.getState(),
classRoom.getUser()
};
tableModel.addRow(rowData);
}
// 设置左侧单元格面板
this.leftCellPanel = new JPanel(new GridLayout(9, 1));
JLabel[] leftLabels = new JLabel[columnNames.length];
this.idPanel = new JPanel();
this.namePanel = new JPanel();
this.numberPanel = new JPanel();
this.addressPanel = new JPanel();
this.stylePanel = new JPanel();
this.statePanel = new JPanel();
this.userPanel = new JPanel();
this.fileButtonPanel = new JPanel();
for (int i = 0; i < columnNames.length; i++) {
leftLabels[i] = new JLabel(columnNames[i] + ":");
}
this.idField = new JTextField(12);
this.idPanel.add(leftLabels[0]);
this.idPanel.add(idField);
this.nameField = new JTextField(12);
this.namePanel.add(leftLabels[1]);
this.namePanel.add(nameField);
this.numberField = new JTextField(12);
this.numberPanel.add(leftLabels[2]);
this.numberPanel.add(numberField);
this.addressField = new JTextField(12);
this.addressPanel.add(leftLabels[3]);
this.addressPanel.add(addressField);
this.styleField = new JTextField(12);
this.stylePanel.add(leftLabels[4]);
this.stylePanel.add(styleField);
this.stateField = new JTextField(12);
this.statePanel.add(leftLabels[5]);
this.statePanel.add(stateField);
this.userField = new JTextField(12);
this.userPanel.add(leftLabels[6]);
this.userPanel.add(userField);
// 设置文件导出按钮面板
this.fileLabel = new JLabel("文件导出格式:");
this.fileComboBox = new JComboBox<>(SelectAll);
this.fileButton = new JButton("导出");
this.fileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FileAction fileAction = new FileAction();
if (Objects.requireNonNull(fileComboBox.getSelectedItem()).toString().equals(".xls")) {
fileAction.fileAction_xls();
}
}
});
this.fileButtonPanel.add(fileLabel);
this.fileButtonPanel.add(fileComboBox);
this.fileButtonPanel.add(fileButton);
// 设置按钮面板
this.addButton = new JButton("添加");
this.addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ActionDao actionDao = new ActionDao();
actionDao.AddDao(idField.getText(), nameField.getText(), numberField.getText(), addressField.getText(), styleField.getText(), stateField.getText(), userField.getText());
Object[] rowData = {
idField.getText(),
nameField.getText(),
numberField.getText(),
addressField.getText(),
styleField.getText(),
stateField.getText(),
userField.getText()
};
tableModel.addRow(rowData);
}
});
this.updateButton = new JButton("修改");
this.updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ActionDao actionDao = new ActionDao();
actionDao.UpdateDao(idField.getText(), nameField
数据库操作代码
1.实现数据库连接
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 数据库连接基础类
*/
public class BaseDao {
// MySQL JDBC驱动程序
private static String driver = "com.mysql.cj.jdbc.Driver";
// 数据库连接URL
private static String url = "jdbc:mysql://localhost:3306/classroomsystem";
// 数据库用户名
private static String jdbc_username = "";// 换成自己的用户名
// 数据库密码
private static String jdbc_password = "";// 换成自己的密码
static {
try {
// 加载驱动程序
Class.forName(driver);
System.out.println("开始连接!");
} catch (ClassNotFoundException e) {
System.out.println("连接错误!");
}
}
/**
* 获取数据库连接
*
* @return 数据库连接对象
* @throws SQLException SQL异常
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, jdbc_username, jdbc_password);
}
}
2.实现对数据库增删改查操作
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 数据库操作类,包含登录、注册、添加、更新、删除等方法
*/
public class ActionDao {
/**
* 登录验证
*
* @param username 用户名
* @param password 密码
* @return 验证结果,"YES"表示验证通过,"NO"表示验证失败
*/
public String LoginDao(String username, String password) {
String sql_login = "SELECT * FROM users WHERE username = ? AND password = ?";
try {
Connection conn = BaseDao.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql_login);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return "YES";
} else {
System.out.println("查询失败!");
return "NO";
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 注册用户
*
* @param username 用户名
* @param password 密码
* @return 注册结果,"YES"表示注册成功,"NO"表示注册失败
*/
public String RegisterDao(String username, String password) {
String sql_ver = "SELECT * FROM users WHERE username = ?";
String sql_reg = "INSERT INTO users (username, password) VALUES (?, ?)";
try {
Connection conn = BaseDao.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql_reg);
int rs_reg = stmt.executeUpdate();
if (rs_reg > 0) {
return "YES";
} else {
System.out.println("注册失败");
return "NO";
}
} catch (SQLException e) {
throw new RuntimeException();
}
}
/**
* 添加教室信息
*
* @param id 教室序号
* @param name 教室编号
* @param number 可容纳数
* @param address 所在楼名
* @param style 教室类型
* @param state 使用状态
* @param user 使用人员
*/
public void AddDao(String id, String name, String number, String address, String style, String state, String user) {
String sql_add = "INSERT INTO classroom VALUES(?, ?, ?, ?, ?, ?, ?)";
try {
Connection conn = BaseDao.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql_add);
stmt.setString(1, id);
stmt.setString(2, name);
stmt.setString(3, number);
stmt.setString(4, address);
stmt.setString(5, style);
stmt.setString(6, state);
stmt.setString(7, user);
int rowAdd = stmt.executeUpdate();
if (rowAdd > 0) {
System.out.println("数据添加成功!");
} else {
System.out.println("数据添加失败!");
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 更新教室信息
*
* @param id 教室序号
* @param name 教室编号
* @param number 可容纳数
* @param address 所在楼名
* @param style 教室类型
* @param state 使用状态
* @param user 使用人员
*/
public void UpdateDao(String id, String name, String number, String address, String style, String state, String user) {
String sql_update = "UPDATE classroom SET name=?,number=?,address=?,style=?,state=?,user=? WHERE id = ?";
try {
Connection conn = BaseDao.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql_update);
stmt.setString(1, name);
stmt.setString(2, number);
stmt.setString(3, address);
stmt.setString(4, style);
stmt.setString(5, state);
stmt.setString(6, user);
stmt.setString(7, id);
int rowsUpdated = stmt.executeUpdate();
System.out.println(rowsUpdated);
if (rowsUpdated > 0) {
System.out.println("更新成功");
} else {
System.out.println("更新失败");
}
} catch (SQLException e) {
throw new RuntimeException();
}
}
/**
* 删除教室信息
*
* @param id 教室序号
*/
public void DeleteDao(String id) {
String sql_delete = "DELETE FROM classroom WHERE id=?";
try {
Connection conn = BaseDao.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql_delete);
stmt.setString(1, id);
3.实现将数据展示在的表格中
package dao;
import base.ClassRoom;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 教室数据访问对象实现类
*/
public class ClassDaoImp implements ClassDao {
/**
* 查询所有教室信息
*
* @return 包含所有教室信息的列表
*/
@Override
public List<ClassRoom> findAll() {
List<ClassRoom> classRooms = new ArrayList<>();
String sql_All = "select * from classroom";
try {
Connection conn = BaseDao.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql_All);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
ClassRoom classRoom = new ClassRoom();
classRoom.setId(rs.getString("id"));
classRoom.setName(rs.getString("name"));
classRoom.setNumber(Integer.valueOf(rs.getString("number")));
classRoom.setAddress(rs.getString("address"));
classRoom.setStyle(rs.getString("style"));
classRoom.setState(rs.getString("state"));
classRoom.setUser(rs.getString("user"));
classRooms.add(classRoom);
}
} catch (SQLException e) {
System.out.println("存在以下问题:" + e);
}
return classRooms;
}
}
package dao;
import base.ClassRoom;
import java.util.List;
public interface ClassDao {
List<ClassRoom> findAll();
}
其他代码
1.实体类
package base;
public class ClassRoom {
private String id;
private String name;
private Integer number;
private String address;
private String style;
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
private String user;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
@Override
public String toString() {
return "ClassRoom{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", number=" + number +
", address='" + address + '\'' +
", style='" + style + '\'' +
", state='" + state + '\'' +
", user='" + user + '\'' +
'}';
}
}
2.Excel表格导出实现
package base;
import dao.BaseDao;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* 文件操作类,用于导出教室使用信息表格
*/
public class FileAction {
// 根据个人更换一个空文件夹路径用来存放导出的表格
public String fileAddress = "D:/ClassroomSystem/Excel//教室使用信息表.xls";
private String columnNames[] = {"教室序号", "教室编号", "可容纳数", "所在楼名", "教室类型", "使用状态", "使用人员"};
public String sql_file = "select * from classroom";
/**
* 导出教室使用信息表格为xls格式
*/
public void fileAction_xls() {
HSSFWorkbook book = new HSSFWorkbook();
HSSFSheet sheet = book.createSheet("教室使用信息表");
try {
Connection conn = BaseDao.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql_file);
ResultSet rs = stmt.executeQuery();
// 创建表头
HSSFRow rowHead = sheet.createRow(0);
for (int i = 0; i < columnNames.length; i++) {
HSSFCell cell = rowHead.createCell(i);
cell.setCellValue(columnNames[i]);
}
// 填充表格数据
int r = 1;
while (rs.next()) {
HSSFRow rowBody = sheet.createRow(r++);
for (int i = 0; i < columnNames.length; i++) {
HSSFCell cell = rowBody.createCell(i);
cell.setCellValue(rs.getString(i + 1));
}
}
// 将数据写入文件
FileOutputStream outputStream = new FileOutputStream(fileAddress);
book.write(outputStream);
book.close();
System.out.println("导入成功!");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
项目总结
该项目主要基于JavaGUI、JDBC和Maven的简易教室后台管理系统。由于个人现阶段能力有限(其实也是有点懒),导致结构比较模糊、项目所实现功能简单及项目中的登录失败提示框等一系列小细节没能实现,界面也是比较简陋(朴素大方),如果有兴趣的小伙伴可以完善一下!在页面、逻辑和结构设计上有更好想法的小伙伴可以在评论区一起讨论!!!