一、目的
通过制作学生信息后台管理系统熟悉java中JDBC和CUI(图形用户接口)的使用。
二、实验工具
1.Eclipse IDE Version: 2020-12 (4.18.0)
2.mysql
3.Navicat Premium 15(数据库管理工具)
4.WindowBuilder(java图形用户界面插件)
具体下载和使用可以参考以下链接:
下载安装WindowBuilder插件教程_jay_musu的博客-CSDN博客
三、需求分析
学生信息后台管理系统,需要实现管理员通过此系统实现对学生信息的增、删、改、查,学生信息包括学号、姓名、年龄、性别、班级、年级等信息,同时,管理员还可以查看学生当前各科成绩的分数以及排名情况,并对其进行修改。除此之外,管理员可以管理课程信息、管理班级信息以及年级信息。
四、设计
本项目中,只是为了熟悉GUI的使用,为了效率则只实现部分功能。结构化设计只展示层次图、数据流图和实体图。其他的包括用例图、数据字典等可以自行按照需求去设计。
1.层次方框图
2.数据流图
只展示顶层图和部分0层图,其他的可自行根据项目去构建
a.顶层图
b.学生信息管理0层图
3. 实体类图
a.设计数据库表,需要满足以下三范式。
(1) 第一范式:所有关系中的每一个分量都必须是不可分割的数据项。第一范式是建立关系数据表的最基本的要求。
(2) 第二范式:满足第一范式的条件,并且每个非键属性都有整个键决定。
(3) 第三范式:满足第二范式,并且每个非键属性不依赖于其他非键属性值。
b.实体类图
c.关系模式
学生(学号,姓名,年龄,性别,班级)
课程(课程编号,课程名)
选课(选课编号,成绩,课程编号,学生学号)
班级(班级编号,班级名,年级编号)
年级(年级编号,年级名)
管理员(管理员编号,用户名,用户账号,用户密码)
五、代码实现
1.创建数据库
CREATE DATABASE `student_management`;
a.建管理员表
CREATE TABLE `student_management`.`admin` (
`admin_id` int NOT NULL COMMENT '管理员ID',
`admin_account` varchar(255) NOT NULL COMMENT '管理员账号',
`admin_name` varchar(255) NOT NULL COMMENT '管理员名称',
`admin_password` varchar(255) NOT NULL COMMENT '管理员密码',
PRIMARY KEY (`admin_id`)
);
b.建学生表
CREATE TABLE `student_management`.`student` (
`student_id` int NOT NULL COMMENT '学生学号',
`student_name` varchar(255) NOT NULL COMMENT '学生姓名',
`student_age` int NOT NULL COMMENT '学生年龄',
`student_sex` varchar(255) NOT NULL COMMENT '学生性别',
`student_class` int NOT NULL COMMENT '学生所属班级',
PRIMARY KEY (`student_id`)
);
c.建课程表
CREATE TABLE `student_management`.`course` (
`course_id` int NOT NULL COMMENT '课程ID',
`course_name` varchar(255) NOT NULL COMMENT '课程名称',
PRIMARY KEY (`course_id`)
);
d.建成绩表
CREATE TABLE `student_management`.`score` (
`score_id` int NOT NULL COMMENT '成绩ID',
`student_id` int NOT NULL COMMENT '成绩对应的学生ID',
`course_id` int NOT NULL COMMENT '成绩所对应的课程ID',
`grade` int NOT NULL COMMENT '成绩分数',
PRIMARY KEY (`score_id`)
);
e.建班级表
CREATE TABLE `student_management`.`class` (
`class_id` int NOT NULL COMMENT '班级ID',
`class_name` varchar(255) NOT NULL COMMENT '班级名称',
`class_year` varchar(255) NOT NULL COMMENT '班级所属年级',
PRIMARY KEY (`class_id`)
);
f.建年级表
CREATE TABLE `student_management`.`year` (
`year_id` int NOT NULL COMMENT '年级ID',
`class_year` varchar(255) NOT NULL COMMENT '年级',
PRIMARY KEY (`year_id`)
);
适当的插入数据进行测试。
2.构建所需要的类
a.管理员类
package model;
public class Admin {
private Integer adminId;//管理员ID
private String adminAccount;//管理员账号
private String adminName;//管理员姓名
private String password;//管理员登录密码
public Integer getAdminId() {
return adminId;
}
public void setAdminId(Integer adminId) {
this.adminId = adminId;
}
public String getAdminAccount() {
return adminAccount;
}
public void setAdminAccount(String adminAccount) {
this.adminAccount = adminAccount;
}
public String getAdminName() {
return adminName;
}
public void setAdminName(String adminName) {
this.adminName = adminName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Admin(Integer adminId, String adminAccount, String adminName, String password) {
super();
this.adminId = adminId;
this.adminAccount = adminAccount;
this.adminName = adminName;
this.password = password;
}
public Admin() {
super();
}
}
b.学生信息类
package model;
public class Student {
private Integer StudentId;//学生ID
private String name;//学生姓名
private Integer age;//学生年龄
private String sex;//学生性别
private String _class;//学生班级
private String year;//学生年级
public Integer getStudentId() {
return StudentId;
}
public void setStudentId(Integer studentId) {
StudentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String get_class() {
return _class;
}
public void set_class(String _class) {
this._class = _class;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public Student(Integer studentId, String name, Integer age, String sex, String _class, String year) {
super();
StudentId = studentId;
this.name = name;
this.age = age;
this.sex = sex;
this._class = _class;
this.year = year;
}
public Student() {
super();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((StudentId == null) ? 0 : StudentId.hashCode());
result = prime * result + ((_class == null) ? 0 : _class.hashCode());
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
result = prime * result + ((year == null) ? 0 : year.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (StudentId == null) {
if (other.StudentId != null)
return false;
} else if (!StudentId.equals(other.StudentId))
return false;
if (_class == null) {
if (other._class != null)
return false;
} else if (!_class.equals(other._class))
return false;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex))
return false;
if (year == null) {
if (other.year != null)
return false;
} else if (!year.equals(other.year))
return false;
return true;
}
@Override
public String toString() {
return "Student [StudentId=" + StudentId + ", name=" + name + ", age=" + age + ", sex=" + sex + ", _class="
+ _class + ", year=" + year + "]";
}
}
c.学生成绩类
package model;
import java.math.BigDecimal;
public class StudentScore {
private Integer rank;//排名
private Integer studentId;//学生ID
private String studentName;//学生姓名
private String className;//学生班级
private String yearName;//学生年级
private Integer chinese;//语文成绩
private Integer math;//数学成绩
private Integer english;//英语成绩
private Integer politics;//思政成绩
private Integer TP;//总分
private BigDecimal average;//平均分
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getYearName() {
return yearName;
}
public void setYearName(String yearName) {
this.yearName = yearName;
}
public Integer getChinese() {
return chinese;
}
public void setChinese(Integer chinese) {
this.chinese = chinese;
}
public Integer getMath() {
return math;
}
public void setMath(Integer math) {
this.math = math;
}
public Integer getEnglish() {
return english;
}
public void setEnglish(Integer english) {
this.english = english;
}
public Integer getPolitics() {
return politics;
}
public void setPolitics(Integer politics) {
this.politics = politics;
}
public Integer getTP() {
return TP;
}
public void setTP(Integer tP) {
TP = tP;
}
public BigDecimal getAverage() {
return average;
}
public void setAverage(BigDecimal average) {
this.average = average;
}
public StudentScore(Integer rank, Integer studentId, String studentName, String className, String yearName,
Integer chinese, Integer math, Integer english, Integer politics, Integer tP, BigDecimal average) {
super();
this.rank = rank;
this.studentId = studentId;
this.studentName = studentName;
this.className = className;
this.yearName = yearName;
this.chinese = chinese;
this.math = math;
this.english = english;
this.politics = politics;
TP = tP;
this.average = average;
}
public StudentScore() {
super();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((TP == null) ? 0 : TP.hashCode());
result = prime * result + ((average == null) ? 0 : average.hashCode());
result = prime * result + ((chinese == null) ? 0 : chinese.hashCode());
result = prime * result + ((className == null) ? 0 : className.hashCode());
result = prime * result + ((english == null) ? 0 : english.hashCode());
result = prime * result + ((math == null) ? 0 : math.hashCode());
result = prime * result + ((politics == null) ? 0 : politics.hashCode());
result = prime * result + ((rank == null) ? 0 : rank.hashCode());
result = prime * result + ((studentId == null) ? 0 : studentId.hashCode());
result = prime * result + ((studentName == null) ? 0 : studentName.hashCode());
result = prime * result + ((yearName == null) ? 0 : yearName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StudentScore other = (StudentScore) obj;
if (TP == null) {
if (other.TP != null)
return false;
} else if (!TP.equals(other.TP))
return false;
if (average == null) {
if (other.average != null)
return false;
} else if (!average.equals(other.average))
return false;
if (chinese == null) {
if (other.chinese != null)
return false;
} else if (!chinese.equals(other.chinese))
return false;
if (className == null) {
if (other.className != null)
return false;
} else if (!className.equals(other.className))
return false;
if (english == null) {
if (other.english != null)
return false;
} else if (!english.equals(other.english))
return false;
if (math == null) {
if (other.math != null)
return false;
} else if (!math.equals(other.math))
return false;
if (politics == null) {
if (other.politics != null)
return false;
} else if (!politics.equals(other.politics))
return false;
if (rank == null) {
if (other.rank != null)
return false;
} else if (!rank.equals(other.rank))
return false;
if (studentId == null) {
if (other.studentId != null)
return false;
} else if (!studentId.equals(other.studentId))
return false;
if (studentName == null) {
if (other.studentName != null)
return false;
} else if (!studentName.equals(other.studentName))
return false;
if (yearName == null) {
if (other.yearName != null)
return false;
} else if (!yearName.equals(other.yearName))
return false;
return true;
}
@Override
public String toString() {
return "StudentScore [rank=" + rank + ", studentId=" + studentId + ", studentName=" + studentName
+ ", className=" + className + ", yearName=" + yearName + ", chinese=" + chinese + ", math=" + math
+ ", english=" + english + ", politics=" + politics + ", TP=" + TP + ", average=" + average + "]";
}
}
3.构建service功能
a.创建SelectService接口
添加项目需要的查询方法声明,实现如下:
package service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import model.Admin;
import model.Student;
public interface SelectService {
//查询管理员信息
//验证管理员登录信息
Admin selectAdminByAccount(String account) throws Exception;
//按班级或年级获取学生信息
ResultSet selectStudentByAny(String classId,String classYear) throws Exception;
//获取所有年级
List<String> selectAllYear() throws Exception;
//按年级获取班级
List<String> selectclassByYear(String year) throws Exception;
//按年级获取年级ID
Integer selectYearIdByYearName(String yearName) throws Exception;
//按班级获取班级ID
Integer selectClassIdByClassName(String className) throws Exception;
//按学号查询学生信息
Student selectStudentByStuId(Integer stuId) throws Exception;
//通过班级查询年级
String selectYearByClassName(String className) throws Exception;
//模糊查询学生信息
ResultSet selectStudentByKey(String key) throws Exception;
//查询学生成绩并通过条件进行排名
ResultSet selectStudentRankByKey(String key,String yearName,String className) throws Exception;
}
b.实现SelectService接口中的方法
package service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import config.DatabaseConnection;
import model.Admin;
import model.Student;
public class SelectServiceImpl implements SelectService{
public Admin selectAdminByAccount(String account) throws Exception {
String sql = "select * from admin where admin_account = ? ";
PreparedStatement preStmt = DatabaseConnection.connection().prepareStatement(sql);
preStmt.setString(1, account);
ResultSet result = preStmt.executeQuery();
Admin admin = null;
while(result.next()) {
admin = new Admin();
admin.setAdminId(result.getInt("admin_id"));
admin.setAdminAccount(result.getString("admin_account"));
admin.setAdminName(result.getString("admin_name"));
admin.setPassword(result.getString("admin_password"));
}
return admin;
}
@Override
public ResultSet selectStudentByAny(String className, String classYear) throws Exception {
String sql = "SELECT\r\n"
+ " student.student_id,\r\n"
+ " student.student_name,\r\n"
+ " student.student_age,\r\n"
+ " student.student_sex,\r\n"
+ " class.class_name,\r\n"
+ " `year`.class_year\r\n"
+ "FROM\r\n"
+ " `year`\r\n"
+ " INNER JOIN class ON `year`.year_id = class.class_year\r\n"
+ " INNER JOIN student ON class.class_id = student.student_class \r\n"
+ "WHERE\r\n"
+ " 1 = 1 ";
if(className != null && !className.equals("")) {
String str = "and class.class_name = " + "'" + className + "'\r\n";
sql += str;
}
if(classYear != null && !classYear.equals("")) {
String str = "and `year`.class_year = " + "'" + classYear + "'\r\n";
sql += str;
}
Statement stmt = DatabaseConnection.connection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
// ResultSet result = stmt.executeQuery(sql);
//
// List<Student> stuList = new ArrayList<Student>();
// while(result.next()) {
// Student stu = new Student();
// stu.setStudentId(result.getInt("student_id"));
// stu.setName(result.getString("student_name"));
// stu.setSex(result.getString("student_sex"));
// stu.set_class(result.getString("class_name"));
// stu.setYear(result.getString("class_year"));
// stuList.add(stu);
// }
return stmt.executeQuery(sql);
}
@Override
public List<String> selectAllYear() throws Exception {
String sql = "select class_year from `year`";
Statement stmt = DatabaseConnection.connection().createStatement();
ResultSet result = stmt.executeQuery(sql);
List<String> yearList = new ArrayList<String>();
while(result.next()) {
yearList.add(result.getString("class_year"));
}
return yearList;
}
@Override
public List<String> selectclassByYear(String year) throws Exception {
String sql ="SELECT\r\n"
+ " class_name \r\n"
+ "FROM\r\n"
+ " class\r\n"
+ " INNER JOIN `year` ON `year`.year_id = class.class_year \r\n"
+ "WHERE\r\n"
+ " 1 = 1 ";
if(year != null && !year.equals("")) {
String str = "AND `year`.class_year = " + "'" + year + "'";
sql += str;
}
Statement stmt = DatabaseConnection.connection().createStatement();
ResultSet result = stmt.executeQuery(sql);
List<String> classList = new ArrayList<String>();
while(result.next()) {
classList.add(result.getString("class_name"));
}
return classList;
}
@Override
public Integer selectYearIdByYearName(String yearName) throws Exception {
String sql = "SELECT year_id FROM `year` WHERE `year`.year_name = " + "'" + yearName + "'";
Statement stmt = DatabaseConnection.connection().createStatement();
ResultSet result = stmt.executeQuery(sql);
Integer yearId = null;
while(result.next()) {
yearId = result.getInt("year_id");
}
return yearId;
}
@Override
public Integer selectClassIdByClassName(String className) throws Exception {
String sql = "SELECT class_id FROM `class` WHERE `class`.class_name = " + "'" + className + "'";
Statement stmt = DatabaseConnection.connection().createStatement();
ResultSet result = stmt.executeQuery(sql);
Integer classId = null;
while(result.next()) {
classId = result.getInt("class_id");
}
return classId;
}
@Override
public Student selectStudentByStuId(Integer stuId) throws Exception {
String sql = "SELECT\r\n"
+ " student.student_id,\r\n"
+ " student.student_name,\r\n"
+ " student.student_age,\r\n"
+ " student.student_sex,\r\n"
+ " class.class_name,\r\n"
+ " `year`.class_year \r\n"
+ "FROM\r\n"
+ " `year`\r\n"
+ " INNER JOIN class ON `year`.year_id = class.class_year\r\n"
+ " INNER JOIN student ON class.class_id = student.student_class \r\n"
+ "WHERE\r\n"
+ "student.student_id = " + stuId;
Statement stmt = DatabaseConnection.connection().createStatement();
ResultSet result = stmt.executeQuery(sql);
Student stu = new Student();
while(result.next()) {
stu.setStudentId(result.getInt("student_id"));
stu.setName(result.getString("student_name"));
stu.setSex(result.getString("student_sex"));
stu.set_class(result.getString("class_name"));
stu.setYear(result.getString("class_year"));
}
return stu;
}
@Override
public String selectYearByClassName(String className) throws Exception {
String sql = "SELECT\r\n"
+ " `year`.class_year y \r\n"
+ "FROM\r\n"
+ " class\r\n"
+ " INNER JOIN `year` ON class.class_year = `year`.year_id \r\n"
+ "WHERE\r\n"
+ " class_name = '"+ className +"'";
Statement stmt = DatabaseConnection.connection().createStatement();
ResultSet result = stmt.executeQuery(sql);
String yearName = null;
while(result.next()) {
yearName = result.getString("y");
}
return yearName;
}
@Override
public ResultSet selectStudentByKey(String key) throws Exception {
String sql = "SELECT\r\n"
+ " student.student_id,\r\n"
+ " student.student_name,\r\n"
+ " student.student_age,\r\n"
+ " student.student_sex,\r\n"
+ " class.class_name,\r\n"
+ " `year`.class_year\r\n"
+ "FROM\r\n"
+ " `year`\r\n"
+ " INNER JOIN class ON `year`.year_id = class.class_year\r\n"
+ " INNER JOIN student ON class.class_id = student.student_class \r\n"
+ "WHERE\r\n"
+ " 1 = 1 ";
if(key != null && !key.equals("")) {
String str1 = "and class.class_name like " + "'%" + key + "%'\r\n";
sql += str1;
String str2 = "or `year`.class_year like " + "'%" + key + "%'\r\n";
sql += str2;
String str3 = "or student.student_name like " + "'%" + key + "%'\r\n";
sql += str3;
}
Statement stmt = DatabaseConnection.connection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
return stmt.executeQuery(sql);
}
@Override
public ResultSet selectStudentRankByKey(String key,String yearName,String className) throws Exception {
String sql = "SELECT\r\n"
+ " ROW_NUMBER() OVER () AS _rank,d.* \r\n"
+ "FROM\r\n"
+ " (\r\n"
+ "SELECT\r\n"
+ " c.student_id,\r\n"
+ " c.student_name,\r\n"
+ " c.class_name,\r\n"
+ " c.class_year,\r\n"
+ " CAST( c.`大学语文` AS SIGNED ) AS 大学语文,\r\n"
+ " CAST( c.`思政` AS SIGNED ) AS 思政,\r\n"
+ " CAST( c.`英语` AS SIGNED ) AS 英语,\r\n"
+ " CAST( c.`高数` AS SIGNED ) AS 高数,\r\n"
+ " CAST(( c.`大学语文` + c.`思政` + c.`英语` + c.`高数` ) AS SIGNED ) AS TP,\r\n"
+ " CAST(((\r\n"
+ " c.`大学语文` + c.`思政` + c.`英语` + c.`高数` \r\n"
+ " ) / 4 \r\n"
+ " ) AS DECIMAL ( 3, 1 )) AS average \r\n"
+ " FROM\r\n"
+ " (\r\n"
+ " SELECT\r\n"
+ " b.student_id,\r\n"
+ " b.student_name,\r\n"
+ " b.class_name,\r\n"
+ " b.class_year,\r\n"
+ " MAX( b.`大学语文` ) AS '大学语文',\r\n"
+ " MAX( b.`思政` ) AS `思政`,\r\n"
+ " MAX( b.`高数` ) AS `高数`,\r\n"
+ " MAX( b.`英语` ) AS `英语` \r\n"
+ " FROM\r\n"
+ " (\r\n"
+ " SELECT\r\n"
+ " a.student_id,\r\n"
+ " a.student_name,\r\n"
+ " a.class_name,\r\n"
+ " a.class_year,\r\n"
+ " CASE\r\n"
+ " \r\n"
+ " WHEN a.course_name = '英语' THEN\r\n"
+ " a.grade ELSE '' \r\n"
+ " END AS 英语,\r\n"
+ " CASE\r\n"
+ " \r\n"
+ " WHEN a.course_name = '高数' THEN\r\n"
+ " a.grade ELSE '' \r\n"
+ " END AS 高数,\r\n"
+ " CASE\r\n"
+ " \r\n"
+ " WHEN a.course_name = '大学语文' THEN\r\n"
+ " a.grade ELSE '' \r\n"
+ " END AS 大学语文,\r\n"
+ " CASE\r\n"
+ " \r\n"
+ " WHEN a.course_name = '思政' THEN\r\n"
+ " a.grade ELSE '' \r\n"
+ " END AS 思政 \r\n"
+ " FROM\r\n"
+ " (\r\n"
+ " SELECT\r\n"
+ " student.student_id,\r\n"
+ " student.student_name,\r\n"
+ " course.course_name,\r\n"
+ " score.grade,\r\n"
+ " class.class_name,\r\n"
+ " `year`.class_year \r\n"
+ " FROM\r\n"
+ " student\r\n"
+ " INNER JOIN score ON student.student_id = score.student_id\r\n"
+ " INNER JOIN course ON course.course_id = score.course_id\r\n"
+ " INNER JOIN class ON student.student_class = class.class_id\r\n"
+ " INNER JOIN `year` ON `year`.year_id = class.class_year \r\n"
+ " ) a \r\n"
+ " GROUP BY\r\n"
+ " a.student_id,\r\n"
+ " a.course_name \r\n"
+ " ) b \r\n"
+ " GROUP BY\r\n"
+ " b.student_id \r\n"
+ " ) c \r\n"
+ " ) d \r\n"
+ "WHERE\r\n"
+ " 1 = 1 \r\n";
if(className != null && !className.equals("")) {
sql += "and d.class_name = " + "'" + className + "'";
}else {
if(yearName != null && !yearName.equals("")){
sql += "and d.class_year = " + "'" + yearName + "'";
}else {
sql += "and d.class_year = '大一'";//默认大一
}
}
sql += "\r\nORDER BY\r\n";
String str = "d.TP";
if(key != null && !key.equals("")) {
str = "d." + key;
}
sql += str + " DESC";
Statement stmt = DatabaseConnection.connection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet executeQuery = stmt.executeQuery(sql);
return executeQuery;
}
}
项目没有实现课程管理,就以默认的课程来进行管理学生信息和成绩情况了。
查询时可以先在数据库管理软件中编写SQL查询语句进行查询,再直接复制进来。执行SQL语句有多种方法,可以通过Sring拼接的方法,也可以通过Sring的占位符去添加动态值,还可以通过PreparedStatement接口使用“?”占位符去实现动态查询。返回的值统一都为ResultSet,不过若是只有一行数据,可以直接在里面进行处理。
c.删除、增加、修改接口
删除接口
package service;
public interface DeleteService {
void deleteStudentByStuId(Integer stuId) throws Exception;
}
增加接口
package service;
import model.Student;
public interface InsertService {
void InsertStudent(String name,Integer age,String sex,String className) throws Exception;
}
修改接口
package service;
public interface UpdateService {
//修改学生信息
void updateStudent(Integer stuId,String StuName,String stuSex,Integer stuAge,Integer StuClassId) throws Exception;
}
d.实现接口方法
实现删除接口方法
package service;
import java.sql.Statement;
import config.DatabaseConnection;
public class DeleteServiceImpl implements DeleteService{
public void deleteStudentByStuId(Integer stuId) throws Exception{
//删除学生表中学生信息
String sql = "DELETE \r\n"
+ "FROM\r\n"
+ " student \r\n"
+ "WHERE\r\n"
+ " student_id = " + stuId;
//删除成绩表中学生信息
String sql1 = "DELETE \r\n"
+ "FROM\r\n"
+ " score \r\n"
+ "WHERE\r\n"
+ " score.student_id = " + stuId;
Statement stmt = DatabaseConnection.connection().createStatement();
stmt.executeUpdate(sql);
stmt.executeUpdate(sql1);
}
}
实现增加接口方法
package service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import config.DatabaseConnection;
import model.Student;
public class InsertServiceImpl implements InsertService{
//插入一条学生信息
/*
* 先通过年级和班级名字获取对应的Id
* 再插入一条学生信息
*
* */
@Override
public void InsertStudent(String name,Integer age,String sex,String className) throws Exception {
Connection conn = DatabaseConnection.connection();
SelectService service = new SelectServiceImpl();
Integer classId = service.selectClassIdByClassName(className);
String sql = "INSERT INTO student(student_name,student_age,student_sex,student_class) VALUES(?,?,?,?)";
PreparedStatement preStmt = conn.prepareStatement(sql);
preStmt.setString(1,name);
preStmt.setInt(2, age);
preStmt.setString(3,sex);
preStmt.setInt(4,classId);
preStmt.executeUpdate();
}
}
实现修改接口方法
package service;
import java.sql.Connection;
import java.sql.Statement;
import config.DatabaseConnection;
public class UpdateServiceImpl implements UpdateService{
@Override
public void updateStudent(Integer stuId,String stuName, String stuSex, Integer stuAge, Integer StuClassId) throws Exception {
String sql = "UPDATE student SET\r\n";
boolean isHave = false;//判断是否已经添加了修改的语句,如果是则后面的语句需要加上逗号
if(stuName != null && !stuName.equals("")) {
if(isHave) {
sql += ",";
}
sql += "student_name = '" + stuName + "'";
isHave = true;
}
if(stuAge != null && !stuAge.equals("")) {
if(isHave) {
sql += ",";
}
sql += "student_age = " + stuAge;
isHave = true;
}
if(stuSex != null && !stuSex.equals("")) {
if(isHave) {
sql += ",";
}
sql += "student_sex = '" + stuSex + "'";
isHave = true;
}
if(StuClassId != null && !StuClassId.equals("")) {
if(isHave) {
sql += ",";
}
sql += "student_class = " + StuClassId;
isHave = true;
}
sql += "\r\nWHERE\r\n"
+ "student_id = " + stuId;
Statement stmt = DatabaseConnection.connection().createStatement();
stmt.executeUpdate(sql);
}
}
4.连接数据库
创建一个config包,在里面添加一个静态类,负责连接数据库。
package config;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DatabaseConnection {
public static Connection connection() throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/student_management?serverTimezone=UTC";// 注意设置时区,这个连接是8.0版本的mysql。
String username = "root";
String passwords = "root";
Connection c = DriverManager.getConnection(url, username, passwords);
if (c != null) {
System.out.println("数据库连接成功!");
} else {
System.out.println("数据库连接失败!");
}
return c;
}
}
5.创建util包,负责一些工具
a.日期计算工具
package util;
import java.util.Calendar;
public class DataUtil {
//获取年份数组
public static Integer[] getYear() {
Integer[] arr = new Integer[100];
Calendar cal=Calendar.getInstance();
int last = cal.get(Calendar.YEAR);
for (int i = 0; i < arr.length; i++) {
arr[i] = last--;
}
return arr;
}
//获取月份数组
public static Integer[] getMonth() {
Integer[] arr = new Integer[12];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
return arr;
}
//获取日期数组
public static Integer[] getDays(Integer year,Integer month) {
int days = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:days = 31;break;
case 4:
case 6:
case 9:
case 11:days = 30;break;
case 2:days = ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28;break;
default:
throw new IllegalArgumentException("Unexpected value: " + month);
}
Integer[] arr = new Integer[days];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
return arr;
}
//通过出生日期获取年龄
public static Integer getAge(Integer year,Integer month,Integer days) {
Calendar cal=Calendar.getInstance();
int y=cal.get(Calendar.YEAR);
int m=cal.get(Calendar.MONTH);
int d=cal.get(Calendar.DATE);
if((m > month) || (m == month && d > days)) {
return y - year;
}else {
return y - year - 1;
}
}
}
b.ResultSet转化为Object[][]的方法类
package util;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class ResultSetUtil {
public static Object[][] getObjectArray(ResultSet rs) throws Exception{
Object[][] data = null;
rs.last();
int rows = rs.getRow();
data = new Object[rows][];
ResultSetMetaData md = rs.getMetaData();//获取记录集的元数据
int columnCount = md.getColumnCount();//列数
rs.first();
int k = 0;
do {
Object[] row = new Object[columnCount];
for(int i=0; i<columnCount; i++) {
row[i] = rs.getObject(i+1).toString();
}
data[k] = row;
k++;
}while(rs.next());
return data;
}
}
c.List转化为数组的方法类
package util;
import java.util.List;
public class ListToArray {
public static String[] getArray(List<String> list) {
String[] arr = new String[list.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
}
6.创建view包,存放窗体
a.管理员登录窗口
代码:
package view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import model.Admin;
import service.SelectService;
import service.SelectServiceImpl;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTextPane;
import javax.swing.JPasswordField;
import java.awt.Color;
import javax.swing.JTextField;
import java.awt.Toolkit;
import java.awt.SystemColor;
import javax.swing.ImageIcon;
public class Login extends JFrame {
private JPanel contentPane;
private JPasswordField txtPassword;
private JTextField txtUserName;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Login() {
setBackground(Color.WHITE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 290);
contentPane = new JPanel();
contentPane.setBackground(new Color(47, 79, 79));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("登录");
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("宋体", Font.BOLD, 18));
lblNewLabel.setBounds(0, 0, 436, 71);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("用户名:");
lblNewLabel_1.setForeground(Color.WHITE);
lblNewLabel_1.setIcon(null);
lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
lblNewLabel_1.setBounds(81, 80, 58, 23);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("密 码:");
lblNewLabel_2.setForeground(Color.WHITE);
lblNewLabel_2.setHorizontalAlignment(SwingConstants.RIGHT);
lblNewLabel_2.setBounds(81, 131, 58, 23);
contentPane.add(lblNewLabel_2);
JButton btnNewButton = new JButton("登录");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userName = txtUserName.getText();
String password = txtPassword.getText();
if(userName.equals("") || password.equals("") || password.equals(null)) {
JOptionPane.showMessageDialog(null, "用户名或密码为空!");
}else {
Admin admin = null;
SelectService select = new SelectServiceImpl();
try {
admin = select.selectAdminByAccount(userName);
} catch (Exception e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
if(admin != null) {
if(admin.getPassword().equals(password)) {
JOptionPane.showMessageDialog(null, "登录成功!");
close();
new Management().setVisible(true);
}else {
JOptionPane.showMessageDialog(null, "您输入的密码错误!");
}
}else {
JOptionPane.showMessageDialog(null, "您输入的账号错误!");
}
}
}
});
btnNewButton.setFont(new Font("华文仿宋", Font.BOLD, 13));
btnNewButton.setBackground(Color.WHITE);
btnNewButton.setBounds(168, 193, 97, 23);
contentPane.add(btnNewButton);
txtPassword = new JPasswordField();
txtPassword.setBounds(149, 131, 164, 23);
contentPane.add(txtPassword);
txtUserName = new JTextField();
txtUserName.setBounds(149, 81, 164, 21);
contentPane.add(txtUserName);
txtUserName.setColumns(10);
JLabel lblNewLabel_3 = new JLabel("");
lblNewLabel_3.setIcon(new ImageIcon("D:\\guigu\\homework\\student_anagement\\images\\user_icon_copy.png"));
lblNewLabel_3.setBounds(64, 80, 14, 23);
contentPane.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("");
lblNewLabel_4.setIcon(new ImageIcon("D:\\guigu\\homework\\student_anagement\\images\\lock_icon_copy.png"));
lblNewLabel_4.setBounds(64, 131, 14, 23);
contentPane.add(lblNewLabel_4);
}
public void close() {
this.setVisible(false);
}
}
图形界面
b.学生管理窗口
代码:
package view;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.BorderLayout;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import model.Student;
import service.DeleteService;
import service.DeleteServiceImpl;
import service.SelectService;
import service.SelectServiceImpl;
import util.ListToArray;
import util.ResultSetUtil;
import javax.swing.JLabel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.CardLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.SystemColor;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.List;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JList;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;
public class Management extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTable table;
private String className = null;
private String classYear = null;
private DeleteService delete = new DeleteServiceImpl();
private JTable table_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Management frame = new Management();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Management() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 764, 573);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.WHITE);
tabbedPane.addTab("学生管理", null, panel_1, null);
JPanel panel_4 = new JPanel();
panel_4.setBackground(new Color(250, 250, 210));
JButton btnNewButton = new JButton("查询");
btnNewButton.setForeground(Color.BLACK);
btnNewButton.setBackground(Color.WHITE);
btnNewButton.setFont(new Font("宋体", Font.BOLD, 14));
textField = new JTextField();
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("查询:");
lblNewLabel.setFont(new Font("宋体", Font.BOLD, 14));
//获取年级信息
SelectService select = new SelectServiceImpl();
List<String> yearList = null;
try {
yearList = select.selectAllYear();
} catch (Exception e) {
e.printStackTrace();
}
String[] yearArray = null;
//如果年级不为空,则将其转化为数组
if(yearList != null) {
yearArray = ListToArray.getArray(yearList);
}
JComboBox comboBox = new JComboBox(yearArray);
//获取当前选中的年级
String year = (String) comboBox.getSelectedItem();
System.out.println(year);
List<String> classList = null;
//通过年级获取班级
try {
classList = select.selectclassByYear(year);
} catch (Exception e) {
e.printStackTrace();
}
String[] classArray = null;
if(classList != null) {
classArray = ListToArray.getArray(classList);
}
JComboBox comboBox_1 = new JComboBox(classArray);
//为第一个添加下拉框添加监听
//控制第二个下拉框的值
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
comboBox_1.removeAllItems();
//获取当前选中的年级
String year = (String) comboBox.getSelectedItem();
List<String> classList = null;
//通过年级获取班级
try {
classList = select.selectclassByYear(year);
} catch (Exception e) {
e.printStackTrace();
}
String[] classArray = null;
if(classList != null) {
classArray = ListToArray.getArray(classList);
}
for (int i = 0; i < classArray.length; i++) {
comboBox_1.addItem(classArray[i]);
}
String yearName = (String)comboBox.getSelectedItem();
String className = (String)comboBox_1.getSelectedItem();
Object[][] data = updateStudentTable(className,yearName);
table.setModel(new DefaultTableModel(
data,
new String[] {
"学号", "姓名", "年龄", "性别", "班级", "年级"
}
));
table.updateUI();
}
});
//为第二个下拉框添加监听
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String yearName = (String)comboBox.getSelectedItem();
String className = (String)comboBox_1.getSelectedItem();
Object[][] data = updateStudentTable(className,yearName);
table.setModel(new DefaultTableModel(
data,
new String[] {
"学号", "姓名", "年龄", "性别", "班级", "年级"
}
));
table.updateUI();
}
});
GroupLayout gl_panel_4 = new GroupLayout(panel_4);
gl_panel_4.setHorizontalGroup(
gl_panel_4.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel_4.createSequentialGroup()
.addContainerGap(112, Short.MAX_VALUE)
.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
.addGap(33)
.addComponent(comboBox_1, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
.addGap(86)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 166, GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addComponent(btnNewButton)
.addGap(55))
);
gl_panel_4.setVerticalGroup(
gl_panel_4.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_4.createSequentialGroup()
.addGap(20)
.addGroup(gl_panel_4.createParallelGroup(Alignment.BASELINE)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(btnNewButton)
.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE))
.addContainerGap(30, Short.MAX_VALUE))
);
panel_4.setLayout(gl_panel_4);
JPanel panel_5 = new JPanel();
panel_5.setBackground(SystemColor.scrollbar);
JButton btnNewButton_1 = new JButton("添加学生");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new AddStudent().setVisible(true);
}
});
JButton btnNewButton_2 = new JButton("删除学生");
JButton btnNewButton_3 = new JButton("修改学生信息");
JButton btnNewButton_4 = new JButton("退出系统");
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
close();
}
});
JButton btnNewButton_5 = new JButton("刷新信息");
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[][] data = updateStudentTable(null,null);
table.setModel(new DefaultTableModel(
data,
new String[] {
"学号", "姓名", "年龄", "性别", "班级", "年级"
}
));
table.updateUI();
}
});
GroupLayout gl_panel_5 = new GroupLayout(panel_5);
gl_panel_5.setHorizontalGroup(
gl_panel_5.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_5.createSequentialGroup()
.addGroup(gl_panel_5.createParallelGroup(Alignment.LEADING)
.addComponent(btnNewButton_1, GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
.addGroup(gl_panel_5.createSequentialGroup()
.addGap(2)
.addGroup(gl_panel_5.createParallelGroup(Alignment.LEADING)
.addComponent(btnNewButton_3, GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
.addComponent(btnNewButton_2, GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE)
.addComponent(btnNewButton_5, GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
.addComponent(btnNewButton_4, GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE))))
.addContainerGap())
);
gl_panel_5.setVerticalGroup(
gl_panel_5.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_5.createSequentialGroup()
.addGap(75)
.addComponent(btnNewButton_1)
.addGap(41)
.addComponent(btnNewButton_2)
.addGap(42)
.addComponent(btnNewButton_3)
.addGap(44)
.addComponent(btnNewButton_5)
.addGap(46)
.addComponent(btnNewButton_4)
.addContainerGap(93, Short.MAX_VALUE))
);
panel_5.setLayout(gl_panel_5);
JScrollPane scrollPane = new JScrollPane();
Object[][] data = updateStudentTable(null,null);
table = new JTable();
table.setModel(new DefaultTableModel(
data,
new String[] {
"学号", "姓名", "年龄", "性别", "班级", "年级"
}
));
JPanel panel = new JPanel();
tabbedPane.addTab("学生排名", null, panel, null);
JPanel panel_6 = new JPanel();
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panel_6, GroupLayout.PREFERRED_SIZE, 727, GroupLayout.PREFERRED_SIZE)
.addGap(32))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(panel_6, GroupLayout.DEFAULT_SIZE, 521, Short.MAX_VALUE)
.addContainerGap())
);
Object[][] data1 = updateScoreByKey(null, null, null);
table_1 = new JTable();
table_1.setEnabled(false);
table_1.setModel(new DefaultTableModel(
data1,
new String[] {
"排名", "学号", "姓名","年级","班级", "语文", "数学", "英语","思政","总分","平均分"
}
));
JLabel lblNewLabel_1 = new JLabel("选择年级和班级:");
//获取年级信息
SelectService select2 = new SelectServiceImpl();
List<String> yearList2 = null;
try {
yearList = select.selectAllYear();
} catch (Exception e) {
e.printStackTrace();
}
String[] yearArray2 = null;
//如果年级不为空,则将其转化为数组
if(yearList != null) {
yearArray2 = ListToArray.getArray(yearList);
}
JComboBox comboBox_2 = new JComboBox(yearArray2);
//获取当前选中的年级
String year2 = (String) comboBox_2.getSelectedItem();
System.out.println(year);
List<String> classList2 = null;
//通过年级获取班级
try {
classList2 = select.selectclassByYear(year);
} catch (Exception e) {
e.printStackTrace();
}
classList.add(0, "全部");
String[] classArray2 = null;
if(classList != null) {
classArray2 = ListToArray.getArray(classList);
}
JComboBox comboBox_3 = new JComboBox(classArray2);
String[] crouse = {"全部","大学语文","高数","思政","英语"};
JComboBox comboBox_4 = new JComboBox(crouse);
comboBox_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String yearName = (String)comboBox_2.getSelectedItem();
String className = (String)comboBox_3.getSelectedItem();
String key = (String)comboBox_4.getSelectedItem();
if(key != null && key.equals("全部")) key = null;
if(className != null && className.equals("全部")) className = null;
Object[][] data = updateScoreByKey(key,yearName,className);
table_1.setModel(new DefaultTableModel(
data,
new String[] {
"排名", "学号", "姓名","年级","班级", "语文", "数学", "英语","思政","总分","平均分"
}
));
table_1.updateUI();
}
});
JLabel lblNewLabel_2 = new JLabel("按单科排名:");
comboBox_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
comboBox_3.removeAllItems();
//获取当前选中的年级
String year = (String) comboBox_2.getSelectedItem();
List<String> classList = null;
//通过年级获取班级
try {
classList = select.selectclassByYear(year);
} catch (Exception e) {
e.printStackTrace();
}
classList.add(0,"全部");
String[] classArray = null;
if(classList != null) {
classArray = ListToArray.getArray(classList);
}
for (int i = 0; i < classArray.length; i++) {
comboBox_3.addItem(classArray[i]);
}
String yearName = (String)comboBox_2.getSelectedItem();
Object[][] data = updateScoreByKey(null,yearName,null);
table_1.setModel(new DefaultTableModel(
data,
new String[] {
"排名", "学号", "姓名","年级","班级", "语文", "数学", "英语","思政","总分","平均分"
}
));
table_1.updateUI();
}
});
//为第二个下拉框添加监听
comboBox_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String yearName = (String)comboBox_2.getSelectedItem();
String className = (String)comboBox_3.getSelectedItem();
if(className != null && className.equals("全部")) {
className = null;
}
Object[][] data = updateScoreByKey(null,yearName,className);
table_1.setModel(new DefaultTableModel(
data,
new String[] {
"排名", "学号", "姓名","年级","班级", "语文", "数学", "英语","思政","总分","平均分"
}
));
table_1.updateUI();
}
});
JPanel panel_3 = new JPanel();
JButton btnNewButton_6 = new JButton("退出");
btnNewButton_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
close();
}
});
JLabel lblNewLabel_3 = new JLabel("成绩排名");
lblNewLabel_3.setFont(new Font("宋体", Font.BOLD, 15));
lblNewLabel_3.setHorizontalAlignment(SwingConstants.CENTER);
GroupLayout gl_panel_6 = new GroupLayout(panel_6);
gl_panel_6.setHorizontalGroup(
gl_panel_6.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_6.createSequentialGroup()
.addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 749, Short.MAX_VALUE)
.addContainerGap())
.addGroup(gl_panel_6.createSequentialGroup()
.addGap(14)
.addComponent(lblNewLabel_1)
.addGap(18)
.addComponent(comboBox_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(36)
.addComponent(comboBox_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(50)
.addGroup(gl_panel_6.createParallelGroup(Alignment.LEADING)
.addComponent(lblNewLabel_3, GroupLayout.PREFERRED_SIZE, 107, GroupLayout.PREFERRED_SIZE)
.addGroup(gl_panel_6.createSequentialGroup()
.addComponent(lblNewLabel_2, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(comboBox_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(125)
.addComponent(btnNewButton_6, GroupLayout.PREFERRED_SIZE, 71, GroupLayout.PREFERRED_SIZE)))
.addGap(129))
);
gl_panel_6.setVerticalGroup(
gl_panel_6.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_6.createSequentialGroup()
.addContainerGap()
.addComponent(lblNewLabel_3, GroupLayout.PREFERRED_SIZE, 55, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_panel_6.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_1)
.addComponent(comboBox_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblNewLabel_2)
.addComponent(comboBox_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(btnNewButton_6))
.addGap(18)
.addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
.addContainerGap())
);
JScrollPane scrollPane_1 = new JScrollPane();
GroupLayout gl_panel_3 = new GroupLayout(panel_3);
gl_panel_3.setHorizontalGroup(
gl_panel_3.createParallelGroup(Alignment.TRAILING)
.addGroup(Alignment.LEADING, gl_panel_3.createSequentialGroup()
.addComponent(scrollPane_1, GroupLayout.PREFERRED_SIZE, 722, GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);
gl_panel_3.setVerticalGroup(
gl_panel_3.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_3.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE))
);
panel_3.setLayout(gl_panel_3);
panel_6.setLayout(gl_panel_6);
panel.setLayout(gl_panel);
JPanel panel_2 = new JPanel();
tabbedPane.addTab("学生成绩管理", null, panel_2, null);
//修改学生信息
btnNewButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int index = table.getSelectedRow();
if(index != -1) {
String key = (String) table.getValueAt(index, 0);
Integer classId = Integer.parseInt(key.strip());
new UpdateStudent(classId).setVisible(true);
}
}
});
//删除学生信息
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int[] arr = table.getSelectedRows();
int n = JOptionPane.showConfirmDialog(null, "是否删除?", "Title",JOptionPane.YES_NO_OPTION);
if(n == 0) {
for (int i = 0; i < arr.length; i++) {
String key = (String) table.getValueAt(arr[i], 0);
Integer classId = Integer.parseInt(key.strip());
try {
delete.deleteStudentByStuId(classId);
Object[][] data = updateStudentTable(null,null);
table.setModel(new DefaultTableModel(
data,
new String[] {
"学号", "姓名", "年龄", "性别", "班级", "年级"
}
));
table.updateUI();
} catch (Exception e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
}
});
//条件查询
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String key = textField.getText();
Object[][] data = updateByselect(key);
table.setModel(new DefaultTableModel(
data,
new String[] {
"学号", "姓名", "年龄", "性别", "班级", "年级"
}
));
table.updateUI();
}
});
scrollPane.setViewportView(table);
GroupLayout gl_panel_1 = new GroupLayout(panel_1);
gl_panel_1.setHorizontalGroup(
gl_panel_1.createParallelGroup(Alignment.LEADING)
.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, 750, GroupLayout.PREFERRED_SIZE)
.addGroup(gl_panel_1.createSequentialGroup()
.addComponent(panel_5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 633, GroupLayout.PREFERRED_SIZE))
);
gl_panel_1.setVerticalGroup(
gl_panel_1.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_1.createSequentialGroup()
.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
.addComponent(panel_5, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 456, GroupLayout.PREFERRED_SIZE)))
);
panel_1.setLayout(gl_panel_1);
scrollPane_1.setViewportView(table_1);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, 745, Short.MAX_VALUE)
.addContainerGap())
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
contentPane.setLayout(gl_contentPane);
}
/**
* @return
*/
private Object[][] updateStudentTable(String className,String classYear) {
//查询所有学生信息
Object[][] data = null;
SelectService select = new SelectServiceImpl();
try {
ResultSet rs = select.selectStudentByAny(className, classYear);
if(rs.next()) {
data = ResultSetUtil.getObjectArray(rs);
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return data;
}
private Object[][] updateByselect(String key) {
//查询所有学生信息
Object[][] data = null;
SelectService select = new SelectServiceImpl();
try {
ResultSet rs = select.selectStudentByKey(key);
data = ResultSetUtil.getObjectArray(rs);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return data;
}
private Object[][] updateScoreByKey(String key,String yearName,String className){
//查询所有学生信息
Object[][] data = null;
SelectService select = new SelectServiceImpl();
try {
ResultSet rs = select.selectStudentRankByKey(key, yearName, className);
if(rs.next()) {
data = ResultSetUtil.getObjectArray(rs);
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return data;
}
public void close() {
this.setVisible(false);
}
}
图形界面
c.添加学生窗口
代码:
package view;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import service.InsertService;
import service.InsertServiceImpl;
import service.SelectService;
import service.SelectServiceImpl;
import util.DataUtil;
import util.ListToArray;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.awt.Color;
import javax.swing.JToggleButton;
import java.awt.Font;
public class AddStudent extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddStudent frame = new AddStudent();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AddStudent() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 351, 386);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
JLabel lblNewLabel_5 = new JLabel("添加学生信息");
lblNewLabel_5.setFont(new Font("宋体", Font.BOLD, 15));
lblNewLabel_5.setHorizontalAlignment(SwingConstants.CENTER);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(89)
.addComponent(lblNewLabel_5, GroupLayout.PREFERRED_SIZE, 121, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(23, Short.MAX_VALUE))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addContainerGap()
.addComponent(lblNewLabel_5, GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 312, GroupLayout.PREFERRED_SIZE)
.addGap(42))
);
JLabel lblNewLabel = new JLabel("姓名:");
lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblNewLabel_1 = new JLabel("出生日期:");
lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblNewLabel_2 = new JLabel("性别:");
lblNewLabel_2.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblNewLabel_3 = new JLabel("年级:");
lblNewLabel_3.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblNewLabel_4 = new JLabel("班级:");
lblNewLabel_4.setHorizontalAlignment(SwingConstants.RIGHT);
JButton btnNewButton = new JButton("添加");
btnNewButton.setBackground(Color.WHITE);
//获取年级信息
SelectService select = new SelectServiceImpl();
List<String> yearList = null;
try {
yearList = select.selectAllYear();
} catch (Exception e) {
e.printStackTrace();
}
String[] yearArray = null;
//如果年级不为空,则将其转化为数组
if(yearList != null) {
yearArray = ListToArray.getArray(yearList);
}
//初始化年级下拉框的值
JComboBox comboBox = new JComboBox(yearArray);
comboBox.setBackground(Color.WHITE);
//获取当前选中的年级
String year = (String) comboBox.getSelectedItem();
System.out.println(year);
List<String> classList = null;
//通过年级获取班级
try {
classList = select.selectclassByYear(year);
} catch (Exception e) {
e.printStackTrace();
}
String[] classArray = null;
if(classList != null) {
classArray = ListToArray.getArray(classList);
}
//初始化第二个下拉框的值
JComboBox comboBox_1 = new JComboBox(classArray);
comboBox_1.setBackground(Color.WHITE);
//为第一个添加下拉框添加监听
//控制第二个下拉框的值
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
comboBox_1.removeAllItems();
//获取当前选中的年级
String year = (String) comboBox.getSelectedItem();
System.out.println(year);
List<String> classList = null;
//通过年级获取班级
try {
classList = select.selectclassByYear(year);
} catch (Exception e) {
e.printStackTrace();
}
String[] classArray = null;
if(classList != null) {
classArray = ListToArray.getArray(classList);
}
for (int i = 0; i < classArray.length; i++) {
comboBox_1.addItem(classArray[i]);
}
}
});
textField = new JTextField();
textField.setColumns(10);
//获取年份数组并添加到下拉框中
JComboBox comboBox_2 = new JComboBox(DataUtil.getYear());
comboBox_2.setBackground(Color.WHITE);
//获取月份数组并添加到下拉框中
JComboBox comboBox_3 = new JComboBox(DataUtil.getMonth());
comboBox_3.setBackground(Color.WHITE);
//通过月份获取当月的天数
//获取当前的月份
int m = (int) comboBox_3.getSelectedItem();
//获取年份
int y = (int) comboBox_2.getSelectedItem();
//获取天数并添加到下拉框中
JComboBox comboBox_4 = new JComboBox(DataUtil.getDays(y, m));
comboBox_4.setBackground(Color.WHITE);
comboBox_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
comboBox_3.setSelectedIndex(0);
comboBox_4.setSelectedIndex(0);
}
});
comboBox_3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int month = (int) comboBox_3.getSelectedItem();
//获取年份
int year = (int) comboBox_2.getSelectedItem();
Integer[] days = DataUtil.getDays(year, month);
comboBox_4.removeAllItems();
for (int i = 0; i < days.length; i++) {
comboBox_4.addItem(days[i]);
}
}
});
JRadioButton rdbtnNewRadioButton = new JRadioButton("男");
rdbtnNewRadioButton.setBackground(Color.WHITE);
JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("女");
rdbtnNewRadioButton_1.setBackground(Color.WHITE);
ButtonGroup bg = new ButtonGroup();
rdbtnNewRadioButton.setSelected(true);
bg.add(rdbtnNewRadioButton_1);
bg.add(rdbtnNewRadioButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String stuName = textField.getText();
Integer age = DataUtil.getAge(
(Integer)comboBox_2.getSelectedItem(),
(Integer)comboBox_3.getSelectedItem(),
(Integer)comboBox_4.getSelectedItem());
String sex = "";
Enumeration<AbstractButton> radioBtns=bg.getElements();
while (radioBtns.hasMoreElements()) {
AbstractButton btn = radioBtns.nextElement();
if(btn.isSelected()){
sex = btn.getText();
break;
}
}
String className = (String) comboBox_1.getSelectedItem();
if(stuName == null || stuName.equals("")){
JOptionPane.showMessageDialog(null, "姓名不能为空!");
}else {
InsertService insert = new InsertServiceImpl();
try {
insert.InsertStudent(stuName, age, sex, className);
JOptionPane.showMessageDialog(null, "添加成功!");
close();
} catch (Exception e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
});
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(lblNewLabel_4, GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(32)
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING, false)
.addComponent(lblNewLabel_3, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNewLabel_2, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNewLabel_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
.addGap(18)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(comboBox_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(comboBox_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(comboBox_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addComponent(rdbtnNewRadioButton, GroupLayout.PREFERRED_SIZE, 53, GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addComponent(rdbtnNewRadioButton_1, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE))
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 138, GroupLayout.PREFERRED_SIZE))
.addGap(52))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(27)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(24)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_1)
.addComponent(comboBox_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_2)
.addComponent(rdbtnNewRadioButton)
.addComponent(rdbtnNewRadioButton_1))
.addGap(18)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_3)
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_4)
.addComponent(comboBox_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(34)
.addComponent(btnNewButton)
.addGap(47))
);
panel.setLayout(gl_panel);
contentPane.setLayout(gl_contentPane);
}
//关闭窗口
public void close() {
this.setVisible(false);
}
}
图形界面
d.修改学生信息窗口
代码:
package view;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import model.Student;
import service.InsertService;
import service.InsertServiceImpl;
import service.SelectService;
import service.SelectServiceImpl;
import service.UpdateService;
import service.UpdateServiceImpl;
import util.DataUtil;
import util.ListToArray;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.awt.Color;
import javax.swing.JToggleButton;
import java.awt.Font;
public class UpdateStudent extends JFrame {
private JPanel contentPane;
private JTextField textField;
private Integer stuId;//需要修改的学生学号
private SelectService select = new SelectServiceImpl();
private UpdateService update = new UpdateServiceImpl();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UpdateStudent frame = new UpdateStudent(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public UpdateStudent(Integer stuId) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 370, 386);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
JLabel lblNewLabel_5 = new JLabel("修改学生信息");
lblNewLabel_5.setFont(new Font("宋体", Font.BOLD, 15));
lblNewLabel_5.setHorizontalAlignment(SwingConstants.CENTER);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(89)
.addComponent(lblNewLabel_5, GroupLayout.PREFERRED_SIZE, 121, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 325, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(24, Short.MAX_VALUE))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addComponent(lblNewLabel_5, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 312, GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
//获取需要修改学生的信息
Student stu = null;
try {
stu = select.selectStudentByStuId(stuId);
} catch (Exception e2) {
// TODO 自动生成的 catch 块
e2.printStackTrace();
}
JLabel lblNewLabel = new JLabel("姓名:");
lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblNewLabel_1 = new JLabel("出生日期:");
lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblNewLabel_2 = new JLabel("性别:");
lblNewLabel_2.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblNewLabel_3 = new JLabel("年级:");
lblNewLabel_3.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblNewLabel_4 = new JLabel("班级:");
lblNewLabel_4.setHorizontalAlignment(SwingConstants.RIGHT);
JButton btnNewButton = new JButton("确认");
btnNewButton.setBackground(Color.WHITE);
//获取年级信息
List<String> yearList = null;
try {
yearList = select.selectAllYear();
} catch (Exception e) {
e.printStackTrace();
}
String[] yearArray = null;
//如果年级不为空,则将其转化为数组
if(yearList != null) {
yearArray = ListToArray.getArray(yearList);
}
//初始化年级下拉框的值
JComboBox comboBox = new JComboBox(yearArray);
comboBox.setBackground(Color.WHITE);
//获取当前选中的年级
String year = (String) comboBox.getSelectedItem();
System.out.println(year);
List<String> classList = null;
//通过年级获取班级
try {
classList = select.selectclassByYear(year);
} catch (Exception e) {
e.printStackTrace();
}
String[] classArray = null;
if(classList != null) {
classArray = ListToArray.getArray(classList);
}
//初始化第二个下拉框的值
JComboBox comboBox_1 = new JComboBox(classArray);
comboBox_1.setBackground(Color.WHITE);
//为第一个添加下拉框添加监听
//控制第二个下拉框的值
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
comboBox_1.removeAllItems();
//获取当前选中的年级
String year = (String) comboBox.getSelectedItem();
System.out.println(year);
List<String> classList = null;
//通过年级获取班级
try {
classList = select.selectclassByYear(year);
} catch (Exception e) {
e.printStackTrace();
}
String[] classArray = null;
if(classList != null) {
classArray = ListToArray.getArray(classList);
}
for (int i = 0; i < classArray.length; i++) {
comboBox_1.addItem(classArray[i]);
}
}
});
textField = new JTextField();
textField.setColumns(10);
//获取年份数组并添加到下拉框中
JComboBox comboBox_2 = new JComboBox(DataUtil.getYear());
comboBox_2.setBackground(Color.WHITE);
//获取月份数组并添加到下拉框中
JComboBox comboBox_3 = new JComboBox(DataUtil.getMonth());
comboBox_3.setBackground(Color.WHITE);
//通过月份获取当月的天数
//获取当前的月份
int m = (int) comboBox_3.getSelectedItem();
//获取年份
int y = (int) comboBox_2.getSelectedItem();
//获取天数并添加到下拉框中
JComboBox comboBox_4 = new JComboBox(DataUtil.getDays(y, m));
comboBox_4.setBackground(Color.WHITE);
comboBox_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
comboBox_3.setSelectedIndex(0);
comboBox_4.setSelectedIndex(0);
}
});
comboBox_3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int month = (int) comboBox_3.getSelectedItem();
//获取年份
int year = (int) comboBox_2.getSelectedItem();
Integer[] days = DataUtil.getDays(year, month);
comboBox_4.removeAllItems();
for (int i = 0; i < days.length; i++) {
comboBox_4.addItem(days[i]);
}
}
});
JRadioButton rdbtnNewRadioButton = new JRadioButton("男");
rdbtnNewRadioButton.setBackground(Color.WHITE);
JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("女");
rdbtnNewRadioButton_1.setBackground(Color.WHITE);
ButtonGroup bg = new ButtonGroup();
rdbtnNewRadioButton.setSelected(true);
bg.add(rdbtnNewRadioButton_1);
bg.add(rdbtnNewRadioButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String stuName = textField.getText();
Integer age = DataUtil.getAge(
(Integer)comboBox_2.getSelectedItem(),
(Integer)comboBox_3.getSelectedItem(),
(Integer)comboBox_4.getSelectedItem());
String sex = "";
Enumeration<AbstractButton> radioBtns=bg.getElements();
while (radioBtns.hasMoreElements()) {
AbstractButton btn = radioBtns.nextElement();
if(btn.isSelected()){
sex = btn.getText();
break;
}
}
String className = (String) comboBox_1.getSelectedItem();
if(stuName == null || stuName.equals("")){
JOptionPane.showMessageDialog(null, "姓名不能为空!");
}else {
try {
Integer classId = select.selectClassIdByClassName(className);
int n = JOptionPane.showConfirmDialog(null, "是否确认进行修改?", "Title",JOptionPane.YES_NO_OPTION);
if(n == 0) {
update.updateStudent(stuId,stuName, sex, age, classId);
JOptionPane.showMessageDialog(null, "修改成功!");
close();
}
} catch (Exception e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
});
//初始化姓名为所需要修改的学生信息
//因为储存的是年龄不是出生日期,无法计算具体日期则不初始化了
if(stuId != null && !stuId.equals("")) {
//初始化姓名
textField.setText(stu.getName());
//初始化性别
if(stu.getSex().equals("男")) {
rdbtnNewRadioButton.setSelected(true);
}else {
rdbtnNewRadioButton_1.setSelected(true);
}
String yearName = "";
try {
yearName = select.selectYearByClassName(stu.get_class());
} catch (Exception e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
//初始化年级
comboBox.setSelectedItem(yearName);
//初始化班级
comboBox_1.setSelectedItem(stu.get_class());
}
JButton btnNewButton_1 = new JButton("退出");
btnNewButton_1.setBackground(Color.WHITE);
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE)
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING, false)
.addComponent(lblNewLabel_3, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNewLabel_2, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNewLabel_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNewLabel_4, GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)))
.addGap(18))
.addGroup(gl_panel.createSequentialGroup()
.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(comboBox_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(comboBox_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(comboBox_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 138, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addComponent(btnNewButton_1, GroupLayout.PREFERRED_SIZE, 81, GroupLayout.PREFERRED_SIZE)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(rdbtnNewRadioButton, GroupLayout.PREFERRED_SIZE, 53, GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addComponent(rdbtnNewRadioButton_1, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE))))
.addGap(62))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(27)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(24)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_1)
.addComponent(comboBox_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBox_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_2)
.addComponent(rdbtnNewRadioButton)
.addComponent(rdbtnNewRadioButton_1))
.addGap(18)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_3)
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(comboBox_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblNewLabel_4))
.addGap(31)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(btnNewButton)
.addComponent(btnNewButton_1))
.addGap(42))
);
panel.setLayout(gl_panel);
contentPane.setLayout(gl_contentPane);
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
close();
}
});
}
//关闭窗口
public void close() {
this.setVisible(false);
}
}
图形界面
六、测试
1.登录测试
输入错误账户密码
输入正确账号密码
2.学生管理界面测试
输入账户密码正确后,会关闭登录框,然后弹出学生管理窗口
如下:
a.条件查询
b.模糊查询
c. 删除学生
可以选择一个,也可以选择多个进行删除,同时还会更新数据。
3.添加学生测试
添加成功后,需要通过点击学生管理窗口的刷新信息按钮刷新界面。
如图所示,自动生成了一个ID,在数据库将ID属性设为自增,且每次加一就可以完成以上效果。
4.修改窗口测试
选择需要修改的学生,点击修改按钮,即可跳转修改界面
5.排名测试
七、注意事项
1.实体类和ResultSet转换
此程序中,因为JTable控件需要的数据类型为二维数组,但是sql查询返回的是ResultSet类型,则直接将ResultSet转化为Object[][]类型,具体实现在util包中的数据类型转化中。因为查询学生信息和成绩时直接将ResultSet转化为了Object[][],中间并没有使用到model包中的实体类,则可以不用创建对应的实体类,而查询管理员信息时,将获得的管理员信息转化为了实体类对象,所以需要创建一个管理员的实体类。
2.控件取名
在创建控件时,最好将每个控件取上对应的名字,比如标签控件可以叫lblXxx,单行文本框可以叫txtXxx,按钮可以叫btnXxx。如此可以更好的区分控件以及其实现的功能。上述项目中,等写完了才想起来名称没改,控件太多就不改了。
3.控件布局
拖拽控件时,可以将窗体先选好布局,再在窗体布局上添加面板,具体控件可以放在最后布好局的不同面板中。还可以根据需要取设置控件的一些基础属性,如大小(可拖拽放大收缩,需要自定义布局),背景颜色,字体属性等。
4.构建mysql的驱动
java连接数据库,需要用到mysql驱动,可以网搜驱动,然后下载安装,最后得到的如下图:
打开文件,找到如下的驱动包,然后复制
在eclipse的项目文件下新建ilb,然后将驱动包粘贴进去,然后构建路径,如下图所示:
5.引入外部图片
使用标签控件时,可以引入外部图片作为背景,可以让窗体更加美观。首先创建images包,将心仪的图片放进images文件下,然后再通过JLabel控件中的icon引入图片。
6.项目总体结构
八、总结
使用java的GUI实现学生信息后台管理系统,通过更接近于控件源码的实现方式,去了解java中代码的编写,以及控件的具体实现代码,而不是完全依赖于界面上进行拖拽和属性构建。通过构建此系统,熟悉java使用JDBC连接数据库,并实现对数据库的增、删、改、查,不仅可以加强java中对数据库数据的处理能力,还能加强数据库的SQL语句编写能力。除此以外,还能通过类与类之间的方法调用和接口与实现类之间的方法实现,了解掌握ava中类的封装、继承、多态等的原理与使用方式。
版权归原作者 jay_musu 所有, 如有侵权,请联系我们删除。