一.项目介绍:
项目简介:
1.设计思路:采用MVC设计思路
M:model数据模型
V:view视图
C:controller业务逻辑控制,调度模块
2.实现登陆界面:选择登录身份:系统管理员登录、教师登录、学生登录。
3.实现学生信息系统主界面:包括修改密码、退出系统,对学生、班级、教师、课程、选课信息的增删改查,成绩管理等功能的实现。
4.Mysql数据库的连接。
5.实现增删改查,成绩管理功能。
需求功能分析:
二.建包:
com.artisan.dao:对数据库进行操作
com.artisan.model:定义数据库中的表
com.artisan.util:放实用操作、进行数据库连接等
com.artisan.view:可视化界面设计
三.创建名为db_student的数据库:
安装Navicat数据库管理工具
四.做一个登录界面
安装windowbulider插件:可用拖拽方式创建界面
五.创建一个枚举类
package com.artisan.model;
public enum UserType {//让用户登录类型以中文显示
ADMIN("系统管理员",0),TEACHER("教师",1),STUDENT("学生",2);
private String name;
private int index;
private UserType(String name,int index){
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
@Override
public String toString(){//重写
return this.name;
}
}
package com.artisan.util;
public class StringUtil {//判断是否为空
public static boolean isEmpty(String str){
if("".equals(str)|| str == null){//防止出现异常
return true;
}
return false;
}
}
import com.artisan.view;
protected void loginAct(ActionEvent ae) {
// TODO Auto-generated method stub
String userName = userNameTextField.getText().toString();
String password passwordTextField.getText().toString();
UserType selectedItem = (UserType)userTypeComboBox.getSelectedItem();
if(StringUtil.isEmpty(userName)){
JOptionPane.showMessageDialog(this, "用户名不能为空!");
return;
}
if(StringUtil.isEmpty(password)){
JOptionPane.showMessageDialog(this, "密码不能为空!");
return;
}
@Override
public String toString(){
return this.name;
}
}
六.数据库连接以及管理员登录实现
package com.artisan.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbUtil {
private String dbUrl="jdbc:mysql://localhost:3306/db_student?useUnicode=true&characterEncoding=utf8"; // 数据库连接地址
private String dbUserName="root"; // 用户名
private String dbPassword=""; // 密码
private String jdbcName="com.mysql.jdbc.Driver"; // 驱动名称
//获取数据库连接
public Connection getCon(){
try {
Class.forName(jdbcName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection con = null;
try {
con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
//关闭数据库连接
public void closeCon(Connection con)throws Exception{
if(con!=null){
con.close();
}
}
public static void main(String[] args) {
DbUtil dbUtil=new DbUtil();
try {
dbUtil.getCon();
System.out.println("数据库连接成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库连接失败");
}
}
}
package com.artisan.dao;
import java.sql.Connection;
import java.sql.SQLException;
import com.artisan.util.DbUtil;
//创建对数据库连接对象,整个项目与数据库交互都用这个
public class BaseDao {
public Connection con = new DbUtil().getCon();
public void closeDao(){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.artisan.model;
public class Admin{
private int id;
private String name;
private String password;
private String createDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
}
package com.artisan.dao;
import com.artisan.model.Admin;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AdminDao extends BaseDao {
//管理员登陆
public Admin login(Admin admin){
String sql = "select * from s_admin where name=? and password=?";
Admin adminRst = null;
try {
PreparedStatement prst = con.prepareStatement(sql);//把sql语句传给数据库操作对象
prst.setString(1, admin.getName());
prst.setString(2, admin.getPassword());
ResultSet executeQuery = prst.executeQuery();
if(executeQuery.next()){
adminRst = new Admin();
adminRst.setId(executeQuery.getInt("id"));
adminRst.setName(executeQuery.getString("name"));
adminRst.setPassword(executeQuery.getString("password"));
adminRst.setCreateDate(executeQuery.getString("createDate"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return adminRst;
}
接着上面的LoginFrm
package com.artisan.view;
if("系统管理员".equals(selectedItem.getName())){
AdminDao adminDao = new AdminDao();
Admin adminTmp = new Admin();
adminTmp.setName(userName);
adminTmp.setPassword(password);
admin = adminDao.login(adminTmp);
adminDao.closeDao();
if(admin == null){
JOptionPane.showMessageDialog(this, "用户名或密码错误!");
return;
}
JOptionPane.showMessageDialog(this, "欢迎【"+selectedItem.getName()+"】:"+admin.getName()+"登录本系统!");
this.dispose();
new MainFrm(selectedItem, admin).setVisible(true);}
七.学生信息系统主界面设计
同上,以拖拽方式完成
班级管理、教师管理、课程管理等同上
八.修改密码
package com.artisan.view;
public class EditPasswordFrm extends JInternalFrame {
contentPane.setLayout(gl_contentPane);
if("系统管理员".equals(MainFrm.userType.getName())){
Admin admin = (Admin)MainFrm.userObject;
currentUserLabel.setText("【系统管理员】" + admin.getName());
}else if("学生".equals(MainFrm.userType.getName())){
Student student = (Student)MainFrm.userObject;
currentUserLabel.setText("【学生】" + student.getName());
}else{
Teacher teacher = (Teacher)MainFrm.userObject;
currentUserLabel.setText("【学生】" + teacher.getName());
}
}
protected void submitEdit(ActionEvent e) {
// TODO Auto-generated method stub
String oldPassword = oldPasswordTextField.getText().toString();
String newPassword = newPasswordTextField.getText().toString();
String conformPassword = confirmPasswordTextField.getText().toString();
if(StringUtil.isEmpty(oldPassword)){
JOptionPane.showMessageDialog(this, "请填写旧密码!");
return;
}
if(StringUtil.isEmpty(newPassword)){
JOptionPane.showMessageDialog(this, "请填写新密码!");
return;
}
if(StringUtil.isEmpty(conformPassword)){
JOptionPane.showMessageDialog(this, "请确认新密码!");
return;
}
if(!newPassword.equals(conformPassword)){
JOptionPane.showMessageDialog(this, "两次密码输入不一致!");
return;
}
if("系统管理员".equals(MainFrm.userType.getName())){
AdminDao adminDao = new AdminDao();
Admin adminTmp = new Admin();
Admin admin = (Admin)MainFrm.userObject;
adminTmp.setName(admin.getName());
adminTmp.setId(admin.getId());
adminTmp.setPassword(oldPassword);
JOptionPane.showMessageDialog(this, adminDao.editPassword(adminTmp, newPassword));
adminDao.closeDao();
return;
}
if("学生".equals(MainFrm.userType.getName())){
StudentDao studentDao = new StudentDao();
Student studentTmp = new Student();
Student student = (Student)MainFrm.userObject;
studentTmp.setName(student.getName());
studentTmp.setPassword(oldPassword);
studentTmp.setId(student.getId());
JOptionPane.showMessageDialog(this, studentDao.editPassword(studentTmp, newPassword));
studentDao.closeDao();
return;
}
if("教师".equals(MainFrm.userType.getName())){
TeacherDao teacherDao = new TeacherDao();
Teacher teacherTmp = new Teacher();
Teacher teacher = (Teacher)MainFrm.userObject;
teacherTmp.setName(teacher.getName());
teacherTmp.setPassword(oldPassword);
teacherTmp.setId(teacher.getId());
JOptionPane.showMessageDialog(this, teacherDao.editPassword(teacherTmp, newPassword));
teacherDao.closeDao();
return;
}
}
protected void resetValue(ActionEvent ae) {
// TODO Auto-generated method stub
oldPasswordTextField.setText("");
newPasswordTextField.setText("");
confirmPasswordTextField.setText("");
}
}
接着上面的Admin
package com.artisan.dao;
public class AdminDao extends BaseDao {
public String editPassword(Admin admin,String newPassword){
String sql = "select * from s_admin where id=? and password=?";
PreparedStatement prst = null;
int id = 0;
try {
prst = con.prepareStatement(sql);
prst.setInt(1, admin.getId());
prst.setString(2, admin.getPassword());
ResultSet executeQuery = prst.executeQuery();
if(!executeQuery.next()){
String retString = "旧密码错误!";
return retString;
}
id = executeQuery.getInt("id");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}//把sql语句传给数据库操作对象
String retString = "修改失败";
String sqlString = "update s_admin set password = ? where id = ?";
try {
prst = con.prepareStatement(sqlString);
prst.setString(1, newPassword);
prst.setInt(2, id);
int rst = prst.executeUpdate();
if(rst > 0){
retString = "密码修改成功!";
}
} catch (SQLException e){
// TODO Auto-generated catch block
e.printStackTrace();
}//把sql语句传给数据库操作对象
return retString;
}
}
九.从登录界面登录成功,进入学生信息管理系统主界面
package com.artisan.view;
public class LoginFrm extends JFrame {
Admin admin = null;
if("系统管理员".equals(selectedItem.getName())){
AdminDao adminDao = new AdminDao();
Admin adminTmp = new Admin();
adminTmp.setName(userName);
adminTmp.setPassword(password);
admin = adminDao.login(adminTmp);
adminDao.closeDao();
if(admin == null){
JOptionPane.showMessageDialog(this, "用户名或密码错误!");
return;
}
JOptionPane.showMessageDialog(this, "欢迎【"+selectedItem.getName()+"】:"+admin.getName()+"登录本系统!");
this.dispose();
new MainFrm(selectedItem, admin).setVisible(true);
}
}
protected void restValue(ActionEvent ae) {
// TODO Auto-generated method stub
userNameTextField.setText("");
passwordTextField.setText("");
userTypeComboBox.setSelectedIndex(0);
}
}
十.学生信息的管理
创建学生页面
package com.artisan.model;
public class Student {
private int id;
private String name;
private int classId;
private String password;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getClassId() {
return classId;
}
public void setClassId(int classId) {
this.classId = classId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String toString(){
return this.name;
}
}
package com.artisan.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.artisan.model.Admin;
import com.artisan.model.Student;
import com.artisan.model.StudentClass;
import com.artisan.util.StringUtil;
public class StudentDao extends BaseDao {
public boolean addStudent(Student student){
String sql = "insert into s_student values(null,?,?,?,?)";
try {
java.sql.PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setString(1, student.getName());
preparedStatement.setInt(2, student.getClassId());
preparedStatement.setString(3, student.getPassword());
preparedStatement.setString(4, student.getSex());
if(preparedStatement.executeUpdate() > 0)return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public List<Student> getStudentList(Student student){
List<Student> retList = new ArrayList<Student>();
StringBuffer sqlString = new StringBuffer("select * from s_student");
if(!StringUtil.isEmpty(student.getName())){
sqlString.append(" and name like '%"+student.getName()+"%'");
}
if(student.getClassId() != 0){
sqlString.append(" and classId ="+student.getClassId());
}
try {
PreparedStatement preparedStatement = con.prepareStatement(sqlString.toString().replaceFirst("and", "where"));
ResultSet executeQuery = preparedStatement.executeQuery();
while(executeQuery.next()){
Student s = new Student();
s.setId(executeQuery.getInt("id"));
s.setName(executeQuery.getString("name"));
s.setClassId(executeQuery.getInt("classId"));
s.setSex(executeQuery.getString("sex"));
s.setPassword(executeQuery.getString("password"));
retList.add(s);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retList;
}
public boolean delete(int id){
String sql = "delete from s_student where id=?";
try {
PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setInt(1, id);
if(preparedStatement.executeUpdate() > 0){
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public boolean update(Student student){
String sql = "update s_student set name=?, classId=?,sex=?,password=? where id=?";
try {
PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setString(1, student.getName());
preparedStatement.setInt(2, student.getClassId());
preparedStatement.setString(3, student.getSex());
preparedStatement.setString(4, student.getPassword());
preparedStatement.setInt(5, student.getId());
if(preparedStatement.executeUpdate() > 0){
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public String editPassword(Student student,String newPassword){
String sql = "select * from s_student where id=? and password=?";
PreparedStatement prst = null;
int id = 0;
try {
prst = con.prepareStatement(sql);
prst.setInt(1, student.getId());
prst.setString(2, student.getPassword());
ResultSet executeQuery = prst.executeQuery();
if(!executeQuery.next()){
String retString = "旧密码错误!";
return retString;
}
id = executeQuery.getInt("id");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}//把sql语句传给数据库操作对象
String retString = "修改失败";
String sqlString = "update s_student set password = ? where id = ?";
try {
prst = con.prepareStatement(sqlString);
prst.setString(1, newPassword);
prst.setInt(2, id);
int rst = prst.executeUpdate();
if(rst > 0){
retString = "密码修改成功!";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//把sql语句传给数据库操作对象
return retString;
}
public Student login(Student student){
String sql = "select * from s_student where name=? and password=?";
Student studentRst = null;
try {
PreparedStatement prst = con.prepareStatement(sql);//把sql语句传给数据库操作对象
prst.setString(1, student.getName());
prst.setString(2, student.getPassword());
ResultSet executeQuery = prst.executeQuery();
if(executeQuery.next()){
studentRst = new Student();
studentRst.setId(executeQuery.getInt("id"));
studentRst.setClassId(executeQuery.getInt("classId"));
studentRst.setName(executeQuery.getString("name"));
studentRst.setPassword(executeQuery.getString("password"));
studentRst.setSex(executeQuery.getString("sex"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return studentRst;
}
}
十一.学生信息的添加
package com.artisan.view;`
public class AddStudentFrm extends JInternalFrame {
protected void resetValue(ActionEvent ae) {
// TODO Auto-generated method stub
studentNameTextField.setText("");
studentPasswordField.setText("");
studentClassComboBox.setSelectedIndex(0);
sexButtonGroup.clearSelection();
studentSexManRadioButton.setSelected(true);
}
protected void studentAddAct(ActionEvent ae) {
// TODO Auto-generated method stub
String studentName = studentNameTextField.getText().toString();
String studentPassword = studentPasswordField.getText().toString();
if(StringUtil.isEmpty(studentName)){
JOptionPane.showMessageDialog(this, "请填写学生姓名!");
return;
}
if(StringUtil.isEmpty(studentPassword)){
JOptionPane.showMessageDialog(this, "请填写密码!");
return;
}
StudentClass sc = (StudentClass)studentClassComboBox.getSelectedItem();
String sex = studentSexManRadioButton.isSelected() ? studentSexManRadioButton.getText().toString() : studentSexFemalRadioButton.getText().toString();
Student student = new Student();
student.setName(studentName);
student.setClassId(sc.getId());
student.setPassword(studentPassword);
student.setSex(sex);
StudentDao studentDao = new StudentDao();
if(studentDao.addStudent(student)){
JOptionPane.showMessageDialog(this, "添加成功!");
}else{
JOptionPane.showMessageDialog(this, "添加失败!");
}
resetValue(ae);
}
private void setStudentClassInfo(){
ClassDao classDao = new ClassDao();
List<StudentClass> classList = classDao.getClassList(new StudentClass());
for (StudentClass sc : classList) {
studentClassComboBox.addItem(sc);
}
classDao.closeDao();
}
}
十二.学生信息删除功能
package com.artisan.view;
public class ManageStudentFrm extends JInternalFrame {
protected void deleteStudent(ActionEvent ae) {
// TODO Auto-generated method stub
int row = studentListTable.getSelectedRow();
if(row == -1){
JOptionPane.showMessageDialog(this, "请选中要删除的数据!");
return;
}
if(JOptionPane.showConfirmDialog(this, "您确定删除么?") != JOptionPane.OK_OPTION){
return;
}
StudentDao studentDao = new StudentDao();
if(studentDao.delete(Integer.parseInt(studentListTable.getValueAt(row, 0).toString()))){
JOptionPane.showMessageDialog(this, "删除成功!");
}else{
JOptionPane.showMessageDialog(this, "删除失败!");
}
studentDao.closeDao();
setTable(new Student());
}
十三.修改学生信息
package com.artisan.view;
public class ManageStudentFrm extends JInternalFrame {
protected void selectedTableRow(MouseEvent me) {
// TODO Auto-generated method stub
DefaultTableModel dft = (DefaultTableModel) studentListTable.getModel();
editStudentNameTextField.setText(dft.getValueAt(studentListTable.getSelectedRow(), 1).toString());
editStudentPasswordPasswordField.setText(dft.getValueAt(studentListTable.getSelectedRow(), 4).toString());
String className = dft.getValueAt(studentListTable.getSelectedRow(), 2).toString();
for(int i=0;i<editStudentClassComboBox.getItemCount();i++){
StudentClass sc = (StudentClass)editStudentClassComboBox.getItemAt(i);
if(className.equals(sc.getName())){
editStudentClassComboBox.setSelectedIndex(i);
}
}
String sex = dft.getValueAt(studentListTable.getSelectedRow(), 3).toString();
editSexButtonGroup.clearSelection();
if(sex.equals(editStudentSexManRadioButton.getText()))editStudentSexManRadioButton.setSelected(true);
if(sex.equals(editStudentSexFemalRadioButton.getText()))editStudentSexFemalRadioButton.setSelected(true);
}
protected void searchStudent(ActionEvent ae) {
// TODO Auto-generated method stub
Student student = new Student();
student.setName(serachStudentNameTextField.getText().toString());
StudentClass sc = (StudentClass)searchStudentComboBox.getSelectedItem();
student.setClassId(sc.getId());
setTable(student);
}
private void setTable(Student student){
if("学生".equals(MainFrm.userType.getName())){
Student s = (Student)MainFrm.userObject;
student.setName(s.getName());
}
DefaultTableModel dft = (DefaultTableModel) studentListTable.getModel();
dft.setRowCount(0);
StudentDao studentDao = new StudentDao();
List<Student> studentList = studentDao.getStudentList(student);
for (Student s : studentList) {
Vector v = new Vector();
v.add(s.getId());
v.add(s.getName());
v.add(getClassNameById(s.getClassId()));
v.add(s.getSex());
v.add(s.getPassword());
dft.addRow(v);
}
studentDao.closeDao();
}
private void setStudentClassInfo(){
ClassDao classDao = new ClassDao();
studentClassList = classDao.getClassList(new StudentClass());
for (StudentClass sc : studentClassList) {
searchStudentComboBox.addItem(sc);
editStudentClassComboBox.addItem(sc);
}
classDao.closeDao();
}
private String getClassNameById(int id){
for (StudentClass sc : studentClassList) {
if(sc.getId() == id)return sc.getName();
}
return "";
}
private void setAuthority(){
if("学生".equals(MainFrm.userType.getName())){
Student s = (Student)MainFrm.userObject;
serachStudentNameTextField.setText(s.getName());
serachStudentNameTextField.setEnabled(false);
deleteStudentButton.setEnabled(false);
for(int i=0;i<searchStudentComboBox.getItemCount();i++){
StudentClass sc = (StudentClass) searchStudentComboBox.getItemAt(i);
if(sc.getId() == s.getClassId()){
searchStudentComboBox.setSelectedIndex(i);
break;
}
}
searchStudentComboBox.setEnabled(false);
for(int i=0;i<editStudentClassComboBox.getItemCount();i++){
StudentClass sc = (StudentClass) editStudentClassComboBox.getItemAt(i);
if(sc.getId() == s.getClassId()){
editStudentClassComboBox.setSelectedIndex(i);
break;
}
}
editStudentClassComboBox.setEnabled(false);
}
}
}
十四.成绩录入界面设计
十五.数据库成绩录入
package com.artisan.model;
public class Score {
private int id;
private int student_id;
private int course_id;
private int score;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public int getCourse_id() {
return course_id;
}
public void setCourse_id(int course_id) {
this.course_id = course_id;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
package com.artisan.view;
public class AddScoreFrm extends JInternalFrame {
protected void submitAct(ActionEvent ae) {
// TODO Auto-generated method stub
int score = 0;
try {
score = Integer.parseInt(scoreTextField.getText().toString());
} catch (Exception e) {
// TODO: handle exception
JOptionPane.showMessageDialog(this, "成绩必须输入大于0的整数!");
return;
}
if(score <= 0){
JOptionPane.showMessageDialog(this, "成绩必须输入大于0的整数!");
return;
}
Student student = (Student) studentComboBox.getSelectedItem();
Course course = (Course)courseComboBox.getSelectedItem();
Score scoreObj = new Score();
scoreObj.setStudent_id(student.getId());
scoreObj.setCourse_id(course.getId());
scoreObj.setScore(score);
ScoreDao scoreDao = new ScoreDao();
if(scoreDao.isAdd(scoreObj)){
JOptionPane.showMessageDialog(this, "成绩已经录入,请勿重复录入!");
return;
}if(scoreDao.addScore(scoreObj)){
JOptionPane.showMessageDialog(this, "成绩录入成功!");
scoreTextField.setText("");
}else{
JOptionPane.showMessageDialog(this, "成绩录入失败!");
}
scoreDao.closeDao();
}
protected void courseChangeAct(ItemEvent ae) {
// TODO Auto-generated method stub
if(ae.getStateChange() == ItemEvent.SELECTED){
setStudentCombox();
}
//JOptionPane.showMessageDialog(this, "changed");
//setStudentCombox();
}
private void setCourseCombox(){
CourseDao courseDao = new CourseDao();
courseList = courseDao.getCourseList(new Course());
courseDao.closeDao();
for (Course course : courseList) {
if("教师".equals(MainFrm.userType.getName())){
Teacher teacher = (Teacher)MainFrm.userObject;
if(course.getTeacher_id() == teacher.getId()){
courseComboBox.addItem(course);
}
continue;
}
//执行到这里一定是超级管理员身份
courseComboBox.addItem(course);
}
}
private void setStudentCombox(){
studentComboBox.removeAllItems();
StudentDao studentDao = new StudentDao();
studentList = studentDao.getStudentList(new Student());
studentDao.closeDao();
Course course = (Course)courseComboBox.getSelectedItem();
List<Student> selectedCourseStudentList = getSelectedCourseStudentList(course);
for (Student student : studentList) {
for(Student student2 : selectedCourseStudentList){
if(student.getId() == student2.getId())
studentComboBox.addItem(student);
}
}
}
private List<Student> getSelectedCourseStudentList(Course course){
SelectedCourseDao scDao = new SelectedCourseDao();
List<Student> selectedCourseStudentList = scDao.getSelectedCourseStudentList(course);
return selectedCourseStudentList;
}
}
package com.artisan.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.artisan.model.Score;
public class ScoreDao extends BaseDao {
public boolean addScore(Score score){
String sql = "insert into s_score values(null,?,?,?)";
try {
java.sql.PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setInt(1, score.getStudent_id());
preparedStatement.setInt(2, score.getCourse_id());
preparedStatement.setInt(3, score.getScore());
if(preparedStatement.executeUpdate() > 0)return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public List<Score> getScoreList(Score score){
List<Score> retList = new ArrayList<Score>();
StringBuffer sqlString = new StringBuffer("select * from s_score");
if(score.getStudent_id() != 0){
sqlString.append(" and student_id = "+score.getStudent_id());
}
if(score.getCourse_id() != 0){
sqlString.append(" and course_id ="+score.getCourse_id());
}
try {
PreparedStatement preparedStatement = con.prepareStatement(sqlString.toString().replaceFirst("and", "where"));
ResultSet executeQuery = preparedStatement.executeQuery();
while(executeQuery.next()){
Score s = new Score();
s.setId(executeQuery.getInt("id"));
s.setStudent_id(executeQuery.getInt("student_id"));
s.setCourse_id(executeQuery.getInt("course_id"));
s.setScore(executeQuery.getInt("score"));
retList.add(s);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retList;
}
public boolean isAdd(Score score){
String sql = "select * from s_score where student_id=? and course_id = ?";
try {
PreparedStatement prst = con.prepareStatement(sql);//把sql语句传给数据库操作对象
prst.setInt(1, score.getStudent_id());
prst.setInt(2, score.getCourse_id());
ResultSet executeQuery = prst.executeQuery();
if(executeQuery.next()){
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public boolean update(int id,int score){
String sql = "update s_score set score = ? where id=?";
try {
PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setInt(1, score);
preparedStatement.setInt(2, id);
if(preparedStatement.executeUpdate() > 0){
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public boolean delete(int id){
String sql = "delete from s_score where id=?";
try {
PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setInt(1, id);
if(preparedStatement.executeUpdate() > 0){
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public Map<String,String> getStatsInfo(int course_id){
Map<String,String> ret = new HashMap<String,String>();
String sql = "select count(id) as student_num,max(score) as max_score,min(score) as min_score,AVG(score) as mid_score from s_score where course_id = ?";
PreparedStatement preparedStatement;
try {
preparedStatement = con.prepareStatement(sql);
preparedStatement.setInt(1, course_id);
ResultSet executeQuery = preparedStatement.executeQuery();
if(executeQuery.next()){
ret.put("student_num", executeQuery.getInt("student_num")+"");
ret.put("max_score", executeQuery.getInt("max_score")+"");
ret.put("min_score", executeQuery.getInt("min_score")+"");
ret.put("mid_score", executeQuery.getFloat("mid_score")+"");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
}
十六.成绩查询
需要以学生身份登录
package com.artisan.view;
public class ViewScoreFrm extends JInternalFrame {
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
scrollPane.setViewportView(scoreListTable);
getContentPane().setLayout(groupLayout);
setCourseCombox();
initTable();
}
protected void courseChangedAct(ItemEvent ie) {
// TODO Auto-generated method stub
setTable();
}
private void setCourseCombox(){
CourseDao courseDao = new CourseDao();
courseList = courseDao.getCourseList(new Course());
courseDao.closeDao();
Student student = (Student)MainFrm.userObject;
studentNameLabel.setText(student.getName());
SelectedCourse sc = new SelectedCourse();
sc.setStudent_id(student.getId());
SelectedCourseDao scDao = new SelectedCourseDao();
List<SelectedCourse> selectedCourseList = scDao.getSelectedCourseList(sc);
for (SelectedCourse selectedCourse : selectedCourseList) {
courseComboBox.addItem(getCourseById(selectedCourse.getCourse_id()));
}
}
private Course getCourseById(int id){
for (int i = 0; i < courseList.size(); i++) {
if(id == courseList.get(i).getId())return courseList.get(i);
}
return null;
}
private void initTable(){
Student student = (Student)MainFrm.userObject;
//Course course = (Course)courseComboBox.getSelectedItem();
Score score = new Score();
score.setStudent_id(student.getId());
//score.setCourse_id(course.getId());
getScoreList(score);
}
private void setTable(){
Student student = (Student)MainFrm.userObject;
Course course = (Course)courseComboBox.getSelectedItem();
Score score = new Score();
score.setStudent_id(student.getId());
score.setCourse_id(course.getId());
getScoreList(score);
}
private void getScoreList(Score score){
Student student = (Student)MainFrm.userObject;
ScoreDao scoreDao = new ScoreDao();
List<Score> scoreList = scoreDao.getScoreList(score);
DefaultTableModel dft = (DefaultTableModel) scoreListTable.getModel();
dft.setRowCount(0);
for (Score s : scoreList) {
Vector v = new Vector();
v.add(s.getId());
v.add(student.getName());
v.add(getCourseById(s.getCourse_id()));
v.add(s.getScore());
dft.addRow(v);
}
scoreDao.closeDao();
}
}
十七.成绩柱状图
package com.artisan.view;
public class StatsScoreFrm extends JInternalFrame {
protected void barViewAct(ActionEvent ae) {
// TODO Auto-generated method stub
Course course = (Course)courseComboBox.getSelectedItem();
ScoreDao scoreDao = new ScoreDao();
Map<String, String> statsInfo = scoreDao.getStatsInfo(course.getId());
clearPanel();
drawBar(Integer.parseInt(statsInfo.get("student_num")), Integer.parseInt(statsInfo.get("max_score")), Integer.parseInt(statsInfo.get("min_score")), Double.valueOf(statsInfo.get("mid_score")), course.getName());
}
protected void defaultViewAct(ActionEvent ae) {
// TODO Auto-generated method stub
clearPanel();
Course course = (Course)courseComboBox.getSelectedItem();
ScoreDao scoreDao = new ScoreDao();
Map<String, String> statsInfo = scoreDao.getStatsInfo(course.getId());
resetText();
if(statsInfo.size() > 0){
setDefaultPanel(statsInfo.get("student_num"),statsInfo.get("max_score"),statsInfo.get("min_score"),statsInfo.get("mid_score"));
}
}
protected void searchStatsAct(ActionEvent ae) {
// TODO Auto-generated method stub
defaultViewAct(ae);
}
private void setCourseCombox(){
CourseDao courseDao = new CourseDao();
courseList = courseDao.getCourseList(new Course());
courseDao.closeDao();
for (Course course : courseList) {
if("教师".equals(MainFrm.userType.getName())){
Teacher teacher = (Teacher)MainFrm.userObject;
if(course.getTeacher_id() == teacher.getId()){
courseComboBox.addItem(course);
}
continue;
}
//执行到这里一定是超级管理员身份
courseComboBox.addItem(course);
}
}
private void resetText(){
maxScoreTextField.setText("");
minScoreTextField.setText("");
middScoreTextField.setText("");
studentNumTextField.setText("");
}
private void drawBar(int studentNum,int maxScore, int minScore,double midScore,String courseName){
setLanuage();
DefaultCategoryDataset dataSet = new DefaultCategoryDataset();//创建一个数据集
//dataSet.addValue(studentNum, courseName, "学生人数");//添加数据
dataSet.addValue(maxScore, courseName+"(学生人数:"+studentNum+")", "最高分");
dataSet.addValue(minScore, courseName+"(学生人数:"+studentNum+")", "最低分");
dataSet.addValue(midScore, courseName+"(学生人数:"+studentNum+")", "平均分");
//创建一个chart对象,把数据集放进去
JFreeChart chart = ChartFactory.createBarChart3D("学生成绩统计情况", "成绩类别", "成绩分数", dataSet, PlotOrientation.VERTICAL, true, false, false);
//创建一个图标panel
chartPanel= new ChartPanel(chart);
//将图标panel添加到要显示的panel上
chartPanel.setPreferredSize(new Dimension(500,420));
viewPanel.add(chartPanel,BorderLayout.CENTER);
viewPanel.setLayout(new FlowLayout());
viewPanel.updateUI();
viewPanel.repaint();
}
protected void drawCircle(int maxScore, int minScore,double midScore,String courseName) {
// TODO Auto-generated method stub
setLanuage();
DefaultPieDataset dataSet = new DefaultPieDataset();//创建数据集
dataSet.setValue("最高分",maxScore);//设置数据
dataSet.setValue("最低分",minScore);
dataSet.setValue("平均分",midScore);
JFreeChart chart = ChartFactory.createPieChart3D(courseName+"课程学生成绩统计", dataSet, true, true, false);
chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(540,420));
viewPanel.add(chartPanel,BorderLayout.CENTER);
viewPanel.setLayout(new FlowLayout());
viewPanel.updateUI();
viewPanel.repaint();
}
private void setDefaultPanel(String studentNum,String maxScore, String minScore,String midScore){
maxScoreTextField.setText(maxScore);
minScoreTextField.setText(minScore);
middScoreTextField.setText(midScore);
studentNumTextField.setText(studentNum);
//viewPanel.add(maxScoreTextField);
//viewPanel.add(minScoreTextField);
//viewPanel.add(middScoreTextField);
//viewPanel.add(studentNumTextField);
viewPanel.add(defaultPanel);
viewPanel.updateUI();
viewPanel.repaint();
}
private void clearPanel(){
viewPanel.removeAll();
viewPanel.updateUI();
viewPanel.repaint();
}
private void setLanuage(){
//创建主题样式
StandardChartTheme standardChartTheme=new StandardChartTheme("CN");
//设置标题字体
standardChartTheme.setExtraLargeFont(new Font("隶书",Font.BOLD,20));
//设置图例的字体
standardChartTheme.setRegularFont(new Font("宋书",Font.PLAIN,15));
//设置轴向的字体
standardChartTheme.setLargeFont(new Font("宋书",Font.PLAIN,15));
//应用主题样式
ChartFactory.setChartTheme(standardChartTheme);
}
}