基于JavaSwing、MySQL的学生成绩管理系统的设计与实现
1. 系统功能
2. 运行界面
3. 创建数据库、表及输入数据
-- 创建数据库
use mysql;
create database 学生成绩管理系统_柳帅 CHARACTER SET UTF8;
use 学生成绩管理系统_柳帅;
-- 创建用户表_柳帅
CREATE TABLE 用户表_柳帅 (
id bigint(20) NOT NULL AUTO_INCREMENT,
用户名 varchar(50) NOT NULL,
密码 varchar(50) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB;
-- 插入一个管理员用于登录
insert into 用户表_柳帅(用户名,密码) values('admin','123456');
-- 创建学生表
CREATE TABLE `学生成绩表_柳帅` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`学号` varchar(50) NOT NULL,
`姓名` varchar(50) NOT NULL,
`住址` varchar(200) NOT NULL,
`语文` decimal(5,2) NOT NULL DEFAULT '0.00',
`英语` decimal(5,2) NOT NULL DEFAULT '0.00',
`数学` decimal(5,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO 学生成绩表_柳帅(学号, 姓名, 住址, 语文, 英语, 数学) VALUES
('1000', '柳帅制作', '152.136.160.239的服务器', 66, 77, 88),
('1001', '韩雨', '山西省长治市潞州区', 71, 97, 88),
('1002', '张婧怡', '山西省临汾市侯马市红卫厂平阳中公家属区', 96, 81, 92),
('1003', '阿琪', '西藏区那曲市色尼区电力小区', 80, 92, 99),
('1004', '安媛媛', '山西省晋中市祁县紫东小区', 72, 100, 86),
('1005', '陈淑英', '山东省聊城市茌平区新清华园', 80, 82, 95),
('1006', '陈宇帆', '浙江省宁波市宁海县桃源街道沙田路', 84, 89, 87),
('1007', '杜佳庆', '山西省运城市盐湖区', 79, 80, 93),
('1008', '格桑元旦', '西藏区日喀则市桑珠孜区甲措雄乡罗杰村', 73, 95, 88),
('1009', '郝雪雯', '山西大同泰丰里小区D区', 89, 93, 94),
('1010', '荆之楠', '山西省阳泉市高新区宁波路御康山庄区', 95, 82, 91),
('1011', '李海跃', '山东省滨州市邹平市鹤伴春天', 78, 91, 85),
('1012', '李楠', '山西省忻州市繁峙县砂河镇', 97, 86, 99),
('1013', '李若溪', '山东省淄博市张店区共青团西路恒大帝景', 90, 99, 96),
('1014', '李向杰', '海南省临高县临城镇厚禄小区', 88, 97, 95),
('1015', '林宏玉', '江西省新余市分宜县', 100, 89, 90),
('1016', '刘嘉庆', '山西省运城市盐湖区', 76, 92, 93),
('1017', '刘洋', '浙江省金华市婺城区白龙桥镇星河湾', 70, 96, 95),
('1018', '刘翌彤', '山东省济南市平阴县云翠嘉苑', 84, 80, 98),
('1019', '马超飞', '新疆区阿拉尔市十团翠湖雅居', 79, 95, 90),
('1020', '毛荃莹', '山东省济南市市中区', 73, 95, 98),
('1021', '王博雅', '新疆区塔城地区沙湾市润泽三期', 87, 90, 94),
('1022', '王浩然', '山西省长治市襄垣县古韩镇南湖名都小区', 89, 84, 88),
('1023', '王京乐', '山西省太原市晋源区', 80, 89, 89),
('1024', '王楷婷', '山西省吕梁市孝义市贾庄小区', 96, 92, 97),
('1025', '王梦瑶', '山西省临汾市曲沃县', 80, 94, 86),
('1026', '王绍华', '山西省运城市盐湖区', 99, 94, 87),
('1027', '王文静', '山西省运城市闻喜县', 99, 88, 90),
('1028', '闻宇坤', '江西省九江市永修县', 95, 98, 90),
('1029', '武慧珍', '山西省晋中市祁县', 80, 84, 95),
('1030', '武启启', '山西省吕梁市交城县', 75, 89, 91),
('1031', '谢国鑫', '江西省赣州市龙南市里仁镇圳背村', 94, 90, 100),
('1032', '谢佳欣', '海南省海口市美兰区桂林洋盛洋小区', 85, 85, 95),
('1033', '谢世琛', '江西省赣州安远县丰背安置点', 72, 96, 90),
('1034', '徐瑞誉', '山西省临汾市尧都区', 100, 89, 90),
('1035', '许辰阳', '山西省晋中市榆次区玉湖公园', 76, 92, 93),
('1036', '许宇哲', '浙江省台州市温岭市县前街', 70, 96, 95),
('1037', '张露尹', '山西省太原市晋源区', 84, 80, 98),
('1038', '张旭婷', '山西省晋中市平遥县香乐乡薛贤村', 79, 95, 90),
('1039', '张宇婕', '山西省长治市潞州区延安南路清华街', 73, 95, 98),
('1040', '赵文博', '山西省太原市万柏林区上庄街赞城小区', 87, 90, 94),
('1041', '钟杉', '江西省赣州市于都县贡江镇工贸城', 89, 84, 88),
('1042', '周荣泉', '新疆区石河子市17小区合十花园', 80, 89, 89);
E-R图
4. 新建项目
pom.xml
<?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>student-swing</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>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<!--导出包含依赖jar包的可以直接运行的jar-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<archive>
<!--mani不是main-->
<manifest>
<mainClass>cn.ls.App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<!--id自己起的名字-->
<id>one_jar</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
5. 程序包名及其java文件列表
序号 | 包名 | java程序名 | 说明 |
---|---|---|---|
1 | cn.ls.util | DBUtil.java | 进行数据库的连接 |
DimensionUtil.java | 用来获取屏幕的大小 | ||
2 | cn.ls.entity | AdminDO_ls.java | 用户表信息 |
StudentDO_ls.java | 学生表信息 | ||
3 | cn.ls.req | StudentRequest_ls.java | 访问学生信息 |
4 | cn.ls.res | TableDTO_ls.java | 将学生信息储存在表格中 |
5 | cn.ls.view | AddStudentView_ls.java | 主页面的各种组件 |
LoginView_ls.java | 登录页 | ||
MainView_ls.java | 主页面 | ||
UpdateStudentView_ls.java | 主页面的表格体 | ||
6 | cn.ls.view.ext | MainViewCellRender_ls.java | 在每一行的每一列显示之前都会调用 |
MainViewTable_ls.java | 设置关于表格的各种参数(表头,表格体,渲染方式及多行选择) | ||
MainViewTableModel_ls.java | 表格 | ||
7 | cn.ls.service | AdminService_ls.java | 创建一个用户登录接口 |
StudentService_ls.java | 创建一个学生接口 | ||
8 | cn.ls.service.impl | AdminServiceImpl_ls.java | 实现AdminService_cyz接口 |
StudentServiceImpl_ls.java | 实现StudentServiceImpl_cyz.接口 | ||
9 | cn.ls.handler | AddStudentViewHandler_ls.java | 添加按钮的监听器 |
LoginHandler_ls.java | 登录按钮的监听器 | ||
MainViewHander_ls.java | 主页面一系列按钮的监听器 | ||
UpdateStudentViewHander_ls.java | 修改按钮的监听器 | ||
10 | cn.ls | App.java | 系统入口文件(main方法)< |
src\ | ls.png | 图标文件 | |
1个pom.xml文件 | 22个java文件、1个png图标文件 |
(1) 创建cn.ls.util包,包名下创建数据库工具类DBUtil.java
package cn.ls.util;
import java.sql.*;
public class DBUtil {
private static final String URL = "jdbc:mysql://101.42.158.247:3306/学生成绩管理系统_柳帅?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false";
private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String USER_NAME = "root";
private static final String PWD = "*********";
static {
try {
// com.mysql.jdbc.Driver 静态代码块
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取数据库连接
public static Connection getConn() {
try {
return DriverManager.getConnection(URL,USER_NAME,PWD);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void closeConn(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void closePs(PreparedStatement ps) {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void closeRs(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
(2) cn.ls.util.DimensionUtil.java
package cn.ls.util;
import javax.swing.*;
import java.awt.*;
public class DimensionUtil {
public static Rectangle getBounds() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// 保证主界面不会覆盖电脑屏幕的任务栏
Insets screenInsets = Toolkit.getDefaultToolkit()
.getScreenInsets(new JFrame().getGraphicsConfiguration());
Rectangle rectangle = new Rectangle(screenInsets.left, screenInsets.top,
screenSize.width - screenInsets.left - screenInsets.right,
screenSize.height - screenInsets.top - screenInsets.bottom);
return rectangle;
}
}
(3) 创建cn.ls.req包,StudentRequest_ls.java
package cn.ls.req;
public class StudentRequest_ls {
private int pageNow;
private int pageSize;
private int start;
// 查询词
private String searchKey;
public int getStart() {
return (pageNow -1) * pageSize;
}
public int getPageNow() {
return pageNow;
}
public void setPageNow(int pageNow) {
this.pageNow = pageNow;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getSearchKey() {
return searchKey;
}
public void setSearchKey(String searchKey) {
this.searchKey = searchKey;
}
}
(4) 创建cn.ls.res包,包下创建TableDTO_ls.java
package cn.ls.res;
import java.util.Vector;
public class TableDTO_ls {
private Vector<Vector<Object>> data;
private int totalCount;
public Vector<Vector<Object>> getData() {
return data;
}
public void setData(Vector<Vector<Object>> data) {
this.data = data;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
}
(5) 创建cn.ls.entity包,包名下创建实体类Admin_ls.java
package cn.ls.entity;
public class Admin_ls {
private Integer id;
private String 用户名;
private String 密码;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String get用户名() {
return 用户名;
}
public void set用户名(String 用户名) {
this.用户名 = 用户名;
}
public String get密码() {
return 密码;
}
public void set密码(String 密码) {
this.密码 = 密码;
}
}
(6) cn.ls.entity.Student_ls.java
package cn.ls.entity;
public class Student_ls {
private Integer id;
private String 姓名;
private String 学号;
private String 住址;
private Double 语文;
private Double 英语;
private Double 数学;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String get姓名() {
return 姓名;
}
public void set姓名(String 姓名) {
this.姓名 = 姓名;
}
public String get学号() {
return 学号;
}
public void set学号(String 学号) {
this.学号 = 学号;
}
public String get住址() {
return 住址;
}
public void set住址(String 住址) {
this.住址 = 住址;
}
public Double get语文() {
return 语文;
}
public void set语文(Double 语文) {
this.语文 = 语文;
}
public Double get英语() {
return 英语;
}
public void set英语(Double 英语) {
this.英语 = 英语;
}
public Double get数学() {
return 数学;
}
public void set数学(Double 数学) {
this.数学 = 数学;
}
}
(7) 创建cn.ls.service包名,包名下创建接口AdminService_ls.java
package cn.ls.service;
import cn.ls.entity.Admin_ls;
public interface AdminService_ls {
boolean validateAdmin(Admin_ls adminDO);
}
(8) cn.ls.service.StudentService_ls.java 接口文件
package cn.ls.service;
import cn.ls.entity.Student_ls;
import cn.ls.req.StudentRequest_ls;
import cn.ls.res.TableDTO_ls;
public interface StudentService_ls {
TableDTO_ls retrieveStudents(StudentRequest_ls request);
boolean add(Student_ls studentDO);
Student_ls getById(int selectedStudentId);
boolean update(Student_ls studentDO);
boolean delete(int[] selectedStudentIds);
}
(9) 创建包cn.ls.service.impl,包下创建接口实现类AdminServiceImpl_ls.java
package cn.ls.service.impl;
import cn.ls.entity.Admin_ls;
import cn.ls.util.DBUtil;
import cn.ls.service.AdminService_ls;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class AdminServiceImpl_ls implements AdminService_ls {
@Override
public boolean validateAdmin(Admin_ls adminDO) {
String userName = adminDO.get用户名();
String pwdParam = adminDO.get密码();
String sql = "select 密码 from 用户表_柳帅 where 用户名 = ?";
Connection conn = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
conn = DBUtil.getConn();
if (conn == null) {
return false;
}
ps = conn.prepareStatement(sql);
ps.setString(1, userName);
resultSet = ps.executeQuery();
while (resultSet.next()) {
String pwd = resultSet.getString(1);
if (pwdParam.equals(pwd)) {
return true;
}
}
}catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closeRs(resultSet);
DBUtil.closePs(ps);
DBUtil.closeConn(conn);
}
return false;
}
}
(10) cn.ls.service.impl.StudentServiceImpl_ls.java 实现类
package cn.ls.service.impl;
import cn.ls.entity.Student_ls;
import cn.ls.req.StudentRequest_ls;
import cn.ls.res.TableDTO_ls;
import cn.ls.util.DBUtil;
import cn.ls.service.StudentService_ls;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
public class StudentServiceImpl_ls implements StudentService_ls {
@Override
public TableDTO_ls retrieveStudents(StudentRequest_ls request) {
StringBuilder sql = new StringBuilder();
sql.append("select * from 学生成绩表_柳帅 ");
if (request.getSearchKey() != null && !"".equals(request.getSearchKey().trim())) {
sql.append(" where 姓名 like '%"+request.getSearchKey().trim()+"%'");
}
sql.append("order by id asc limit ").append(request.getStart()).append(",")
.append(request.getPageSize());
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
TableDTO_ls returnDTO = new TableDTO_ls();
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement(sql.toString());
rs = ps.executeQuery();
// 查询记录
returnDTO.setData(fillData(rs));
sql.setLength(0);
sql.append("select count(*) from 学生成绩表_柳帅 ");
if (request.getSearchKey() != null && !"".equals(request.getSearchKey().trim())) {
sql.append(" where 姓名 like '%"+request.getSearchKey().trim()+"%'");
}
ps = conn.prepareStatement(sql.toString());
rs = ps.executeQuery();
while (rs.next()) {
int count = rs.getInt(1);
returnDTO.setTotalCount(count);
}
return returnDTO;
}catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closeRs(rs);
DBUtil.closePs(ps);
DBUtil.closeConn(conn);
}
return null;
}
@Override
public boolean add(Student_ls studentDO) {
StringBuilder sql = new StringBuilder();
sql.append(" insert into 学生成绩表_柳帅(姓名,学号,住址,语文,英语,数学) ");
sql.append(" values(?,?,?,?,?,?) ");
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement(sql.toString());
ps.setString(1,studentDO.get姓名());
ps.setString(2,studentDO.get学号());
ps.setString(3,studentDO.get住址());
ps.setDouble(4,studentDO.get语文());
ps.setDouble(5,studentDO.get英语());
ps.setDouble(6,studentDO.get数学());
return ps.executeUpdate() == 1;
}catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closePs(ps);
DBUtil.closeConn(conn);
}
return false;
}
@Override
public Student_ls getById(int selectedStudentId) {
StringBuilder sql = new StringBuilder("select * from 学生成绩表_柳帅 where id = ? ");
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Student_ls studentDO = new Student_ls();
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement(sql.toString());
ps.setInt(1,selectedStudentId);
rs = ps.executeQuery();
while (rs.next()) {
// 处理查出的每一条记录
studentDO.setId(rs.getInt("id"));
studentDO.set姓名(rs.getString("姓名"));
studentDO.set学号(rs.getString("学号"));
studentDO.set住址(rs.getString("住址"));
studentDO.set语文(rs.getDouble("语文"));
studentDO.set英语(rs.getDouble("英语"));
studentDO.set数学(rs.getDouble("数学"));
}
return studentDO;
}catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closeRs(rs);
DBUtil.closePs(ps);
DBUtil.closeConn(conn);
}
return null;
}
@Override
public boolean update(Student_ls studentDO) {
StringBuilder sql = new StringBuilder();
sql.append(" update 学生成绩表_柳帅 set 姓名 = ?,学号=?,住址=?,语文=?,英语=?,数学=? ");
sql.append(" where id =? ");
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement(sql.toString());
ps.setString(1,studentDO.get姓名());
ps.setString(2,studentDO.get学号());
ps.setString(3,studentDO.get住址());
ps.setDouble(4,studentDO.get语文());
ps.setDouble(5,studentDO.get英语());
ps.setDouble(6,studentDO.get数学());
ps.setInt(7,studentDO.getId());
return ps.executeUpdate() == 1;
}catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closePs(ps);
DBUtil.closeConn(conn);
}
return false;
}
@Override
public boolean delete(int[] selectedStudentIds) {
StringBuilder sql = new StringBuilder();
sql.append(" delete from 学生成绩表_柳帅 where id in ( ");
int length = selectedStudentIds.length;
for (int i = 0; i < length; i++) {
if (i == (length - 1)) {
sql.append(" ? ");
}else {
sql.append(" ?, ");
}
}
sql.append(" ) ");
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement(sql.toString());
for (int i = 0; i < length; i++) {
// 设置参数,从1开始
ps.setInt(i + 1, selectedStudentIds[i]);
}
return ps.executeUpdate() == length;
}catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closePs(ps);
DBUtil.closeConn(conn);
}
return false;
}
private Vector<Vector<Object>> fillData(ResultSet rs) throws SQLException {
Vector<Vector<Object>> data = new Vector<>();
while (rs.next()) {
// 处理查出的每一条记录
Vector<Object> oneRecord = new Vector<>();
double cnScore = rs.getDouble("语文");
double enScore = rs.getDouble("英语");
double mathScore = rs.getDouble("数学");
double totalScore = cnScore + enScore + mathScore;
oneRecord.addElement(rs.getInt("id"));
oneRecord.addElement(rs.getString("姓名"));
oneRecord.addElement(rs.getString("学号"));
oneRecord.addElement(rs.getString("住址"));
oneRecord.addElement(cnScore);
oneRecord.addElement(enScore);
oneRecord.addElement(mathScore);
oneRecord.addElement(totalScore);
data.addElement(oneRecord);
}
return data;
}
}
(11) 创建cn.ls.view.ext包,包下创建MainViewTableModel_ls.java
package cn.ls.view.ext;
import javax.swing.table.DefaultTableModel;
import java.util.Vector;
public class MainViewTableModel_ls extends DefaultTableModel {
static Vector<String> columns = new Vector<>();
static {
columns.addElement("编号");
columns.addElement("姓名");
columns.addElement("学号");
columns.addElement("住址");
columns.addElement("语文");
columns.addElement("数学");
columns.addElement("英语");
columns.addElement("总分");
}
private MainViewTableModel_ls() {
super(null,columns);
}
private static MainViewTableModel_ls mainViewTableModel = new MainViewTableModel_ls();
public static MainViewTableModel_ls assembleModel(Vector<Vector<Object>> data) {
mainViewTableModel.setDataVector(data,columns);
return mainViewTableModel;
}
public static void updateModel(Vector<Vector<Object>> data) {
mainViewTableModel.setDataVector(data,columns);
}
public static Vector<String> getColumns() {
return columns;
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
(12) cn.ls.view.ext.MainViewCellRender_ls.java
package cn.ls.view.ext;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
public class MainViewCellRender_ls extends DefaultTableCellRenderer {
// 在每一行的每一列显示之前都会调用
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (row % 2 == 0) {
setBackground(Color.ORANGE); //.LIGHT_GRAY);
} else {
setBackground(Color.WHITE);
}
// 第3列住址左齐
if (column == 3){
setHorizontalAlignment(DefaultTableCellRenderer.LEFT);
}else{
setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
(13) cn.ls.view.ext.MainViewTable_ls.java
package cn.ls.view.ext;
import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.util.Vector;
public class MainViewTable_ls extends JTable {
public MainViewTable_ls() {
JTableHeader tableHeader = getTableHeader();
tableHeader.setFont(new Font(null,Font.BOLD,16));
tableHeader.setForeground(Color.RED);
// 设置表格体
setFont(new Font(null,Font.PLAIN,14));
setForeground(Color.black);
setGridColor(Color.BLACK);
setRowHeight(30);
// 设置多行选择
getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
public void renderRule() {
// 设置表格列的渲染方式
Vector<String> columns = MainViewTableModel_ls.getColumns();
MainViewCellRender_ls render = new MainViewCellRender_ls();
for (int i =0;i < columns.size();i++) {
TableColumn column = getColumn(columns.get(i));
column.setCellRenderer(render);
if (i == 0) {
column.setPreferredWidth(50);
column.setMaxWidth(50);
column.setResizable(false);
}
if (i == 3) {
column.setPreferredWidth(400);
column.setMaxWidth(400);
column.setResizable(true);
}
}
}
}
(14) 创建cn.ls.view包,包下创建添加学生成绩的JDialog程序AddStudentView_ls.java
package cn.ls.view;
import cn.ls.entity.Student_ls;
import cn.ls.handler.AddStuViewHandler_ls;
import javax.swing.*;
import java.awt.*;
public class AddStudentView_ls extends JDialog {
private static final long serialVersionUID = 1L;
JPanel jPanel = new JPanel(new FlowLayout(FlowLayout.CENTER,10,20));
JLabel nameLabel = new JLabel("姓名:",JLabel.RIGHT);
JTextField nameTxt = new JTextField();
JLabel noLabel = new JLabel("学号:",JLabel.RIGHT);
JTextField noTxt = new JTextField();
JLabel homeLabel = new JLabel("住址:",JLabel.RIGHT);
JTextField homeTxt = new JTextField();
JLabel cnLabel = new JLabel("语文成绩:",JLabel.RIGHT);
JTextField cnTxt = new JTextField();
JLabel mathLabel = new JLabel("数学成绩:",JLabel.RIGHT);
JTextField mathTxt = new JTextField();
JLabel enLabel = new JLabel("英语成绩:",JLabel.RIGHT);
JTextField enTxt = new JTextField();
JButton addBtn = new JButton("添加");
AddStuViewHandler_ls addStudentViewHandler;
public AddStudentView_ls(MainView_ls mainView){
super(mainView,"添加学生",true);
addStudentViewHandler = new AddStuViewHandler_ls(this,mainView);
nameLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(nameLabel);
nameTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(nameTxt);
noLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(noLabel);
noTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(noTxt);
homeLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(homeLabel);
homeTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(homeTxt);
cnLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(cnLabel);
cnTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(cnTxt);
enLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(enLabel);
enTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(enTxt);
mathLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(mathLabel);
mathTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(mathTxt);
addBtn.addActionListener(addStudentViewHandler);
jPanel.add(addBtn);
Container contentPane = getContentPane();
contentPane.add(jPanel);
setSize(350,500);
setLocationRelativeTo(null);
// DISPOSE_ON_CLOSE:只销毁当前的窗体
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public Student_ls buildStudentDO() {
Student_ls studentDO = new Student_ls();
studentDO.set姓名(nameTxt.getText());
studentDO.set学号(noTxt.getText());
studentDO.set住址(homeTxt.getText());
studentDO.set语文(Double.valueOf(cnTxt.getText()));
studentDO.set英语(Double.valueOf(enTxt.getText()));
studentDO.set数学(Double.valueOf(mathTxt.getText()));
return studentDO;
}
}
(15) 修改学生成绩的JDialog程序 cn.ls.view.UpdateStudentView_ls.java
package cn.ls.view;
import cn.ls.entity.Student_ls;
import cn.ls.handler.UpdStuViewHandler_ls;
import cn.ls.service.StudentService_ls;
import cn.ls.service.impl.StudentServiceImpl_ls;
import javax.swing.*;
import java.awt.*;
public class UpdateStudentView_ls extends JDialog {
JPanel jPanel = new JPanel(new FlowLayout(FlowLayout.CENTER,10,20));
JLabel idLabel = new JLabel("id:",JLabel.RIGHT);
JTextField idTxt = new JTextField();
JLabel nameLabel = new JLabel("姓名:",JLabel.RIGHT);
JTextField nameTxt = new JTextField();
JLabel noLabel = new JLabel("学号:",JLabel.RIGHT);
JTextField noTxt = new JTextField();
JLabel homeLabel = new JLabel("住址:",JLabel.RIGHT);
JTextField homeTxt = new JTextField();
JLabel cnLabel = new JLabel("语文成绩:",JLabel.RIGHT);
JTextField cnTxt = new JTextField();
JLabel mathLabel = new JLabel("数学成绩:",JLabel.RIGHT);
JTextField mathTxt = new JTextField();
JLabel enLabel = new JLabel("英语成绩:",JLabel.RIGHT);
JTextField enTxt = new JTextField();
JButton updateBtn = new JButton("修改");
UpdStuViewHandler_ls updateStudentViewHandler;
public UpdateStudentView_ls(MainView_ls mainView, int selectedStudentId){
super(mainView,"修改学生",true);
updateStudentViewHandler = new UpdStuViewHandler_ls(this,mainView);
// 查询selectedStudentId对应的记录并回显
StudentService_ls studentService = new StudentServiceImpl_ls();
Student_ls selectedStu = studentService.getById(selectedStudentId);
idLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(idLabel);
idTxt.setPreferredSize(new Dimension(200,30));
idTxt.setText(selectedStu.getId() + "");
// 设置id不可编辑
idTxt.setEnabled(false);
jPanel.add(idTxt);
nameLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(nameLabel);
nameTxt.setPreferredSize(new Dimension(200,30));
nameTxt.setText(selectedStu.get姓名());
jPanel.add(nameTxt);
noLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(noLabel);
noTxt.setPreferredSize(new Dimension(200,30));
noTxt.setText(selectedStu.get学号());
jPanel.add(noTxt);
homeLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(homeLabel);
homeTxt.setText(selectedStu.get住址());
homeTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(homeTxt);
cnLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(cnLabel);
cnTxt.setPreferredSize(new Dimension(200,30));
cnTxt.setText(String.valueOf(selectedStu.get语文()));
jPanel.add(cnTxt);
enLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(enLabel);
enTxt.setPreferredSize(new Dimension(200,30));
enTxt.setText(String.valueOf(selectedStu.get英语()));
jPanel.add(enTxt);
mathLabel.setPreferredSize(new Dimension(80,30));
jPanel.add(mathLabel);
mathTxt.setText(String.valueOf(selectedStu.get数学()));
mathTxt.setPreferredSize(new Dimension(200,30));
jPanel.add(mathTxt);
updateBtn.addActionListener(updateStudentViewHandler);
jPanel.add(updateBtn);
Container contentPane = getContentPane();
contentPane.add(jPanel);
setSize(350,500);
setLocationRelativeTo(null);
// DISPOSE_ON_CLOSE:只销毁当前的窗体
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setResizable(false);
setVisible(true);
}
/*
获取修改后的学生对象
*/
public Student_ls buillspdatedStudentDO() {
Student_ls studentDO = new Student_ls();
studentDO.setId(Integer.valueOf(idTxt.getText()));
studentDO.set姓名(nameTxt.getText());
studentDO.set学号(noTxt.getText());
studentDO.set住址(homeTxt.getText());
studentDO.set语文(Double.valueOf(cnTxt.getText()));
studentDO.set英语(Double.valueOf(enTxt.getText()));
studentDO.set数学(Double.valueOf(mathTxt.getText()));
return studentDO;
}
}
(16) 主控界面JFrame程序 cn.ls.view.MainView_ls.java,并将图标文件1.jpg存储在src下
package cn.ls.view;
import cn.ls.handler.MainViewHandler_ls;
import cn.ls.req.StudentRequest_ls;
import cn.ls.res.TableDTO_ls;
import cn.ls.service.StudentService_ls;
import cn.ls.service.impl.StudentServiceImpl_ls;
import cn.ls.util.DimensionUtil;
import cn.ls.view.ext.MainViewTableModel_ls;
import cn.ls.view.ext.MainViewTable_ls;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class MainView_ls extends JFrame{
JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton addBtn = new JButton("增加");
JButton updateBtn = new JButton("修改");
JButton delBtn = new JButton("删除");
JTextField searchTxt = new JTextField(15);
JButton searchBtn = new JButton("查询");
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JButton preBtn = new JButton("上一页");
JButton nextBtn = new JButton("下一页");
MainViewTable_ls mainViewTable = new MainViewTable_ls();
private int pageNow = 1; // 当前是第几页
private int pageSize = 10; // 一页显示多少条记录
MainViewHandler_ls mainViewHandler;
public MainView_ls() {
super("主界面-学生成绩管理【柳帅研习】for MySQL");
Container contentPane = getContentPane();
Rectangle bounds = DimensionUtil.getBounds();
pageSize = Math.floorDiv(bounds.height,35);
mainViewHandler = new MainViewHandler_ls(this);
// 放置北边的组件
layoutNorth(contentPane);
// 设置中间的jtable
layoutCenter(contentPane);
//放置南边的组件
layoutSouth(contentPane);
// 自定义图标
URL imgUrl = MainView_ls.class.getClassLoader().getResource("ls.png");
setIconImage(new ImageIcon(imgUrl).getImage());
// 根据屏幕大小设置主界面大小
setBounds(bounds);
// 设置窗体完全充满整个屏幕的可见大小
setExtendedState(JFrame.MAXIMIZED_BOTH);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);
}
private void layoutCenter(Container contentPane) {
TableDTO_ls dto = getTableDTO();
MainViewTableModel_ls mainViewTableModel = MainViewTableModel_ls.assembleModel(dto.getData());
// 把jtable和model关联
mainViewTable.setModel(mainViewTableModel);
mainViewTable.renderRule();
JScrollPane jScrollPane = new JScrollPane(mainViewTable);
contentPane.add(jScrollPane,BorderLayout.CENTER);
showPreNext(dto.getTotalCount());
}
private TableDTO_ls getTableDTO() {
StudentService_ls studentService = new StudentServiceImpl_ls();
StudentRequest_ls request = new StudentRequest_ls();
request.setPageNow(pageNow);
request.setPageSize(pageSize);
request.setSearchKey(searchTxt.getText().trim());
TableDTO_ls tableDTO = studentService.retrieveStudents(request);
return tableDTO;
}
private void layoutSouth(Container contentPane) {
preBtn.addActionListener(mainViewHandler);
nextBtn.addActionListener(mainViewHandler);
southPanel.add(preBtn);
southPanel.add(nextBtn);
contentPane.add(southPanel,BorderLayout.SOUTH);
}
/*
设置上一页下一页是否可见
*/
private void showPreNext(int totalCount) {
if (pageNow == 1) {
preBtn.setVisible(false);
} else {
preBtn.setVisible(true);
}
int pageCount = 0;//总共有多少页
if (totalCount % pageSize == 0) {
pageCount = totalCount / pageSize;
} else {
pageCount = totalCount / pageSize + 1;
}
if (pageNow == pageCount) {
nextBtn.setVisible(false);
} else {
nextBtn.setVisible(true);
}
}
private void layoutNorth(Container contentPane) {
// 增加事件监听
addBtn.addActionListener(mainViewHandler);
updateBtn.addActionListener(mainViewHandler);
delBtn.addActionListener(mainViewHandler);
searchBtn.addActionListener(mainViewHandler);
northPanel.add(addBtn);
northPanel.add(updateBtn);
northPanel.add(delBtn);
northPanel.add(searchTxt);
northPanel.add(searchBtn);
contentPane.add(northPanel,BorderLayout.NORTH);
}
public static void main(String[] args) {
new MainView_ls();
}
public void setPageNow(int pageNow) {
this.pageNow = pageNow;
}
public int getPageNow() {
return pageNow;
}
public void reloadTable() {
TableDTO_ls dto = getTableDTO();
MainViewTableModel_ls.updateModel(dto.getData());
mainViewTable.renderRule();
showPreNext(dto.getTotalCount());
}
public int[] getSelectedStudentIds() {
int[] selectedRows = mainViewTable.getSelectedRows();
int[] ids = new int[selectedRows.length];
for (int i = 0; i < selectedRows.length ;i++) {
int rowIndex = selectedRows[i];
Object idObj = mainViewTable.getValueAt(rowIndex, 0);
ids[i] = Integer.valueOf(idObj.toString());
}
return ids;
}
}
(17) 登录界面JFrame程序 cn.ls.view.LoginView_ls.java
package cn.ls.view;
import cn.ls.handler.LoginHandler_ls;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
public class LoginView_ls extends JFrame{
JLabel nameLabel = new JLabel("学生成绩管理 for MySQL",JLabel.CENTER);
SpringLayout springLayout = new SpringLayout();
JPanel centerPanel = new JPanel(springLayout);
JLabel userNameLabel = new JLabel("用户名:");
JTextField userTxt = new JTextField();
JLabel pwdLabel = new JLabel("密 码:");
JPasswordField pwdField = new JPasswordField();
JButton loginBtn = new JButton("登录");
JButton resetBtn = new JButton("重置");
SystemTray systemTray;
TrayIcon trayIcon;
LoginHandler_ls loginHandler;
public LoginView_ls() {
super("JavaSwing项目[柳帅研习] for MySQL8.0.26");
loginHandler = new LoginHandler_ls(this);
Container contentPane = getContentPane();
nameLabel.setFont(new Font("楷体",Font.PLAIN,40));
nameLabel.setPreferredSize(new Dimension(0,80));
Font centerFont = new Font("楷体", Font.PLAIN, 20);
userNameLabel.setFont(centerFont);
userTxt.setPreferredSize(new Dimension(200,30));
pwdLabel.setFont(centerFont);
pwdField.setPreferredSize(new Dimension(200,30));
loginBtn.setFont(centerFont);
resetBtn.setFont(centerFont);
// 把组件加入面板
centerPanel.add(userNameLabel);
centerPanel.add(userTxt);
centerPanel.add(pwdLabel);
centerPanel.add(pwdField);
loginBtn.addActionListener(loginHandler);
// 增加按键事件
loginBtn.addKeyListener(loginHandler);
centerPanel.add(loginBtn);
resetBtn.addActionListener(loginHandler);
centerPanel.add(resetBtn);
// 弹簧布局
layoutCenter();
contentPane.add(nameLabel,BorderLayout.NORTH);
contentPane.add(centerPanel,BorderLayout.CENTER);
if (SystemTray.isSupported()) {
systemTray = SystemTray.getSystemTray();
URL imgUrl = LoginView_ls.class.getClassLoader().getResource("ls.png");
trayIcon = new TrayIcon(new ImageIcon(imgUrl).getImage());
// 设置托盘图片大小自动缩放
trayIcon.setImageAutoSize(true);
try {
systemTray.add(trayIcon);
} catch (AWTException e) {
e.printStackTrace();
}
// 增加最小化时销毁资源
this.addWindowListener(new WindowAdapter() {
@Override
public void windowIconified(WindowEvent e) {
LoginView_ls.this.dispose();
}
});
// 托盘事件监听
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int clickCount = e.getClickCount();
if (clickCount == 1) {
LoginView_ls.this.setExtendedState(JFrame.NORMAL);
}
LoginView_ls.this.setVisible(true);
}
});
}
// 设置loginBtn为默认按钮
getRootPane().setDefaultButton(loginBtn);
// 自定义图标
URL imgUrl = LoginView_ls.class.getClassLoader().getResource("ls.png");
setIconImage(new ImageIcon(imgUrl).getImage());
setSize(600,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
private void layoutCenter() {
// 布局userNameLabel
Spring childWidth = Spring.sum(Spring.sum(Spring.width(userNameLabel), Spring.width(userTxt)),
Spring.constant(20));
int offsetX = childWidth.getValue() / 2 +30;
springLayout.putConstraint(SpringLayout.WEST,userNameLabel,-offsetX,
SpringLayout.HORIZONTAL_CENTER,centerPanel);
springLayout.putConstraint(SpringLayout.NORTH,userNameLabel,20,SpringLayout.NORTH,centerPanel);
// userTxt
springLayout.putConstraint(SpringLayout.WEST,userTxt,20,SpringLayout.EAST,userNameLabel);
springLayout.putConstraint(SpringLayout.NORTH,userTxt,0,SpringLayout.NORTH,userNameLabel);
// pwdLabel
springLayout.putConstraint(SpringLayout.EAST,pwdLabel,0,SpringLayout.EAST,userNameLabel);
springLayout.putConstraint(SpringLayout.NORTH,pwdLabel,20,SpringLayout.SOUTH,userNameLabel);
// pwdField
springLayout.putConstraint(SpringLayout.WEST,pwdField,20,SpringLayout.EAST,pwdLabel);
springLayout.putConstraint(SpringLayout.NORTH,pwdField,0,SpringLayout.NORTH,pwdLabel);
// loginBtn
springLayout.putConstraint(SpringLayout.WEST,loginBtn,50,SpringLayout.WEST,pwdLabel);
springLayout.putConstraint(SpringLayout.NORTH,loginBtn,20,SpringLayout.SOUTH,pwdLabel);
// resetBtn
springLayout.putConstraint(SpringLayout.WEST,resetBtn,50,SpringLayout.EAST,loginBtn);
springLayout.putConstraint(SpringLayout.NORTH,resetBtn,0,SpringLayout.NORTH,loginBtn);
}
public static void main(String[] args) {
new LoginView_ls();
}
public JTextField getUserTxt() {
return userTxt;
}
public JPasswordField getPwdField() {
return pwdField;
}
}
(18 ) 创建cn.ls.handler包,创建AddStuViewHandler_ls.java
package cn.ls.handler;
import cn.ls.entity.Student_ls;
import cn.ls.service.StudentService_ls;
import cn.ls.service.impl.StudentServiceImpl_ls;
import cn.ls.view.AddStudentView_ls;
import cn.ls.view.MainView_ls;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AddStuViewHandler_ls implements ActionListener {
private AddStudentView_ls addStudentView;
private MainView_ls mainView;
public AddStuViewHandler_ls(AddStudentView_ls addStudentView, MainView_ls mainView) {
this.addStudentView = addStudentView;
this.mainView = mainView;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton jButton = (JButton) e.getSource();
String text = jButton.getText();
if ("添加".equals(text)) {
StudentService_ls studentService = new StudentServiceImpl_ls();
Student_ls studentDO = addStudentView.buildStudentDO();
boolean addResult = studentService.add(studentDO);
if (addResult) {
// 重新加载表格查到最新数据
mainView.reloadTable();
addStudentView.dispose();
} else {
JOptionPane.showMessageDialog(addStudentView,"添加失败");
}
}
}
}
(19 ) cn.ls.handler.UpdStuViewHandler_ls.java
package cn.ls.handler;
import cn.ls.entity.Student_ls;
import cn.ls.service.StudentService_ls;
import cn.ls.service.impl.StudentServiceImpl_ls;
import cn.ls.view.MainView_ls;
import cn.ls.view.UpdateStudentView_ls;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class UpdStuViewHandler_ls implements ActionListener {
private UpdateStudentView_ls updateStudentView;
private MainView_ls mainView;
public UpdStuViewHandler_ls(UpdateStudentView_ls updateStudentView, MainView_ls mainView) {
this.updateStudentView = updateStudentView;
this.mainView = mainView;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton jButton = (JButton) e.getSource();
String text = jButton.getText();
if ("修改".equals(text)) {
StudentService_ls studentService = new StudentServiceImpl_ls();
Student_ls studentDO = updateStudentView.buillspdatedStudentDO();
boolean updateResult = studentService.update(studentDO);
if (updateResult) {
// 重新加载表格查到最新数据
mainView.reloadTable();
updateStudentView.dispose();
} else {
JOptionPane.showMessageDialog(updateStudentView,"修改失败");
}
}
}
}
(20) cn.ls.handler.MainViewHandler_ls.java
package cn.ls.handler;
import cn.ls.service.StudentService_ls;
import cn.ls.service.impl.StudentServiceImpl_ls;
import cn.ls.view.AddStudentView_ls;
import cn.ls.view.MainView_ls;
import cn.ls.view.UpdateStudentView_ls;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainViewHandler_ls implements ActionListener {
private MainView_ls mainView;
public MainViewHandler_ls(MainView_ls mainView) {
this.mainView = mainView;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton jButton = (JButton) e.getSource();
String text = jButton.getText();
if ("增加".equals(text)) {
new AddStudentView_ls(mainView);
} else if ("修改".equals(text)) {
int[] selectedStudentIds = mainView.getSelectedStudentIds();
if (selectedStudentIds.length != 1) {
JOptionPane.showMessageDialog(mainView, "一次只能修改一行!");
return;
}
new UpdateStudentView_ls(mainView, selectedStudentIds[0]);
} else if ("删除".equals(text)) {
int[] selectedStudentIds = mainView.getSelectedStudentIds();
if (selectedStudentIds.length == 0) {
JOptionPane.showMessageDialog(mainView, "请选择要删除的行!");
return;
}
int option = JOptionPane.showConfirmDialog(mainView, "你确认要删除选择的" + selectedStudentIds.length + "行吗?",
"确认删除", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) { // 确认
// 执行删除
StudentService_ls studentService = new StudentServiceImpl_ls();
boolean deleteResult = studentService.delete(selectedStudentIds);
if (deleteResult) {
// 重新加载表格查到最新数据
mainView.reloadTable();
} else {
JOptionPane.showMessageDialog(mainView, "删除失败");
}
}
} else if ("查询".equals(text)) {
mainView.setPageNow(1);
mainView.reloadTable();
} else if ("上一页".equals(text)) {
mainView.setPageNow(mainView.getPageNow() - 1);
mainView.reloadTable();
} else if ("下一页".equals(text)) {
mainView.setPageNow(mainView.getPageNow() + 1);
mainView.reloadTable();
}
}
}
(21) cn.ls.handler.LoginHandler_ls.java
package cn.ls.handler;
import cn.ls.entity.Admin_ls;
import cn.ls.service.AdminService_ls;
import cn.ls.service.impl.AdminServiceImpl_ls;
import cn.ls.view.LoginView_ls;
import cn.ls.view.MainView_ls;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class LoginHandler_ls extends KeyAdapter implements ActionListener {
private LoginView_ls loginView;
public LoginHandler_ls(LoginView_ls loginView) {
this.loginView = loginView;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton jButton = (JButton) e.getSource();
String text = jButton.getText();
if ("重置".equals(text)) {
loginView.getUserTxt().setText("");
loginView.getPwdField().setText("");
}else if ("登录".equals(text)) {
login();
}
}
private void login() {
String user = loginView.getUserTxt().getText();
char[] chars = loginView.getPwdField().getPassword();
if (user == null || "".equals(user.trim()) ||
chars == null) {
JOptionPane.showMessageDialog(loginView,"用户名密码必填");
return;
}
String pwd = new String(chars);
System.out.println(user + ":" + pwd);
// 查询db
AdminService_ls adminService = new AdminServiceImpl_ls();
Admin_ls adminDO = new Admin_ls();
adminDO.set用户名(user);
adminDO.set密码(pwd);
boolean flag = adminService.validateAdmin(adminDO);
if (flag) {
// 跳转到主界面并销毁登录界面
new MainView_ls();
loginView.dispose();
}else {
JOptionPane.showMessageDialog(loginView,"用户名密码错误");
}
}
@Override
public void keyPressed(KeyEvent e) {
if (KeyEvent.VK_ENTER == e.getKeyCode()) {
login();
}
}
}
(22) 系统入口程序 cn.ls.App.java
package cn.ls;
import cn.ls.view.LoginView_ls;
public class App {
public static void main( String[] args ) {
new LoginView_ls();
}
}
5. 打包导出、上传
student-swing-1.0-SNAPSHOT-jar-with-dependencies.jar 复制副本并更名为 学生成绩管理系统_柳帅.jar 上传云端供下载运行。
运行命令:
java -jar 学生成绩管理系统_柳帅.jar