本系统实现了用户登录,实现了对学生信息的增删改查,实现了用户修改密码功能,采用MD5加密算法,数据库使用Mysql8.0.13,界面良好。
package com.sjsq.model;
import java.util.ArrayList;
import java.util.List;
/**
* 学生实体类
* @author shuijianshiqing
*
*/
public class Student {
// 学号
private String sId;
// 姓名
private String sName;
// 性别
private String sSex;
// 学院
private String sCollege;
// 专业
private String sMajor;
// 出生日期
private String sBirthday;
// 省份
private String sProvince;
// 电话
private String sPhone;
// 邮箱
private String sEmail;
public Student() {
super();
}
public Student(String sId, String sName, String sSex, String sCollege, String sMajor, String sBirthday,
String sProvince, String sPhone, String sEmail) {
super();
this.sId = sId;
this.sName = sName;
this.sSex = sSex;
this.sCollege = sCollege;
this.sMajor = sMajor;
this.sBirthday = sBirthday;
this.sProvince = sProvince;
this.sPhone = sPhone;
this.sEmail = sEmail;
}
public static List<Student> students=new ArrayList<Student>();
public String getsId() {
return sId;
}
public void setsId(String sId) {
this.sId = sId;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getsSex() {
return sSex;
}
public void setsSex(String sSex) {
this.sSex = sSex;
}
public String getsCollege() {
return sCollege;
}
public void setsCollege(String sCollege) {
this.sCollege = sCollege;
}
public String getsMajor() {
return sMajor;
}
public void setsMajor(String sMajor) {
this.sMajor = sMajor;
}
public String getsBirthday() {
return sBirthday;
}
public void setsBirthday(String sBirthday) {
this.sBirthday = sBirthday;
}
public String getsProvince() {
return sProvince;
}
public void setsProvince(String sProvince) {
this.sProvince = sProvince;
}
public String getsPhone() {
return sPhone;
}
public void setsPhone(String sPhone) {
this.sPhone = sPhone;
}
public String getsEmail() {
return sEmail;
}
public void setsEmail(String sEmail) {
this.sEmail = sEmail;
}
@Override
public String toString() {
return "Student [sId=" + sId + ", sName=" + sName + ", sSex=" + sSex + ", sCollege=" + sCollege + ", sMajor="
+ sMajor + ", sBirthday=" + sBirthday + ", sProvince=" + sProvince + ", sPhone=" + sPhone + ", sEmail="
+ sEmail + "]";
}
}
package com.sjsq.model;
/**
* User实体类
*
* @author shuijianshiqing
*
*/
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
}
package com.sjsq.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.sjsq.model.User;
import com.sjsq.util.DBUtil;
import com.sjsq.util.MD5Util;
import com.sjsq.view.LoginFrame;
/**
* 实现User登录验证及修改密码功能
* @author shuijianshiqing
*
*/
public class UserDao {
// 判断这个用户是否存在
public boolean checkUser(User user){
boolean existFlag=false;
List<User> list=query(user);
// list的size大于0,则用户存在
if(list.size()>0){
existFlag=true;
}
return existFlag;
}
// 查询是否有这个用户,并且返回这个用户
public List<User> query(User user){
List<User> list=new ArrayList<User>();
String sql="select * from user where 1=1 ";
// 判断username是否为空
if(user.getUsername()!=null){
sql+=" and username='"+user.getUsername()+"' ";
}
// 判断password是否为空
if(user.getPassword()!=null){
sql+=" and password='"+user.getPassword()+"' ";
}
System.out.println("------验证用户信息------");
System.out.println("sql语句:"+sql);
DBUtil db=new DBUtil();
ResultSet rs=null;
try {
rs=db.executeQuery(sql);
while(rs.next()){
// 保存用户信息到list中
User userTmp=new User();
userTmp.setUsername(rs.getString("username"));
userTmp.setPassword(rs.getString("password"));
list.add(userTmp);
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
// 关闭数据库
db.close();
}
return list;
}
// 修改密码
public void modifypassword(String password) throws SQLException {
// 获取uname
String username=LoginFrame.uname;
// 密码加密
String s=MD5Util.string2MD5(password);
String sql="update user set password='"+s+"'where username="+"'"+username+"'";
DBUtil db=new DBUtil();
db.executeUpdate(sql);
db.close();
}
}
package com.sjsq.util;
/**
* 字节操作
* @author shuijianshiqing
*
*/
public class ByteUtil {
public static String string2Byte(String str) {
// 定义数组
byte[] bytes = str.getBytes();
return bytes.toString();
}
public static void main(String[] args) {
String str = "123456";
System.out.println(string2Byte(str));
}
}
package com.sjsq.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 实现JDBC的封装
* @author shuijianshiqing
*
*/
public class DBUtil {
//成员变量
private Connection con;
private Statement st;
private ResultSet rs;
private String dirver;
private String url;
private String username;
private String password;
// 构造函数:实现加载数据库驱动,建立连接,创建语句对象
public DBUtil() {
Properties properties = new Properties();
// 获取当前项目根路径
FileUtil fileUtil = new FileUtil();
String filePath = fileUtil.getProperty();
try {
// 把文件转化为输入流
FileInputStream fileInputStream = new FileInputStream(filePath+"/src/resources/db.properties");
// 加载输入流
properties.load(fileInputStream);
// 获取对应参数
dirver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
// 加载驱动
Class.forName(dirver);
// 创建连接
con = DriverManager.getConnection(url, username, password);
// 创建语句对象
st = con.createStatement();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 执行insert,update,delete操作
public boolean executeUpdate(String sql) throws SQLException{
boolean returnFlag=false;
int i=st.executeUpdate(sql);
// 判断操作行数是否大于0
if(i>0){
returnFlag=true;
}
return returnFlag;
}
// 执行select操作
public ResultSet executeQuery(String sql) throws SQLException{
rs=st.executeQuery(sql);
// 返回操作结果
return rs;
}
// 释放资源
public void close(){
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
}
}
public static void testSelect() {
// 测试数据库连接
DBUtil dbUtil = new DBUtil();
String sql = "select * from test";
try {
ResultSet rs = dbUtil.executeQuery(sql);
while(rs.next()) {
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println(username+"-->"+password);
}
} catch (SQLException e) {
e.printStackTrace();
}
dbUtil.close();
}
public static void testInsert() {
// 测试数据库连接
DBUtil dbUtil = new DBUtil();
String sql = "insert into test values('sjsq1','123456')";
try {
Boolean executeFlag = dbUtil.executeUpdate(sql);
if (executeFlag) {
System.out.println("插入数据成功");
}else {
System.out.println("插入数据失败");
}
} catch (SQLException e) {
e.printStackTrace();
}
dbUtil.close();
}
// 测试
public static void main(String[] args) {
// 获取当前路径
FileUtil fileUtil = new FileUtil();
String filePath = fileUtil.getProperty();
System.out.println(filePath);
testSelect();
}
}
package com.sjsq.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 采用MD5加密解密
* @author shuijianshiqing
*
*/
public class MD5Util {
// MD5加密
public static String string2MD5(String source){
// 获取MessageDigest对象
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 执行加密操作
byte[] bytes = source.getBytes();
// MD5算法:得到的目标字节数组的特点,长度固定为16
byte[] md5Bytes = messageDigest.digest(bytes);
// 十六进制的字符
char[] chars = new char[] {
'0', '1', '2', '3', '4', '5',
'6', '7' , '8', '9', 'A', 'B', 'C', 'D', 'E','F' };
StringBuffer sb = new StringBuffer();
// 处理成十六进制的字符串(通常)
for (byte bb : md5Bytes) {
sb.append(chars[(bb >> 4) & 15]);
sb.append(chars[bb & 15]);
}
return sb.toString();
}
// 测试主函数
public static void main(String args[]) {
System.out.println(string2MD5("123456"));
}
}
package com.sjsq.view;
import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import com.sjsq.model.User;
import com.sjsq.util.MD5Util;
import com.sjsq.dao.UserDao;
public class LoginFrame extends JFrame implements ActionListener {
public static String uname = null;
public static String pwd = null;
String username, password, login, quit;
// 登录标签
private JLabel loginJLabel;
private JPanel jContentPane = null;
private JButton jButtonLogin = null;
private JButton jButtonExit = null;
private JTextField jTextFieldUserName = null;
private JTextField jTextFieldPassWord = null;
// 登录用户名
static int storeUserId;
// 图片
public JLabel jLabel_Image = null;
// 登录用户名
public static String storeUserame = null;
// 登录密码
public static String storeUserPassword = null;
// 重新登陆标记
static boolean RELOAD = true;
private JLabel jLabelUserName = null;
private JLabel jLabelPassWord = null;
int index;
public LoginFrame() {
// 设置背景
setForeground(new Color(255, 255, 255));
this.setResizable(false);
this.setSize(800, 500);
this.setTitle("极客大学学生信息管理系统");
this.setLocationRelativeTo(null);
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");// 使用windows外观
} catch (Exception e) {
e.printStackTrace();
}
loginJLabel = new JLabel("极客大学学生信息管理系统");
Font font = new Font("微软雅黑",Font.BOLD,40);
loginJLabel.setFont(font);
loginJLabel.setBounds(180,100,650, 50);
loginJLabel.setForeground(Color.DARK_GRAY);
getContentPane().add(loginJLabel);
Font font2 = new Font("微软雅黑",Font.BOLD,15);
jLabelPassWord = new JLabel();
jLabelPassWord.setFont(font2);
jLabelPassWord.setBounds(new Rectangle(300, 250, 71, 29));
jLabelPassWord.setText("密 码:");
jLabelUserName = new JLabel();
jLabelUserName.setBounds(new Rectangle(300, 300, 71, 29));
jLabelUserName.setFont(font2);
jLabelUserName.setText("用户名:");
// 账号输入框
jTextFieldUserName = new JTextField(20);
jTextFieldUserName.setBounds(new Rectangle(360, 250, 154, 33));
// 密码输入框
jTextFieldPassWord = new JPasswordField();
jTextFieldPassWord.setBounds(new Rectangle(360, 300, 154, 33));
// 登录
jButtonLogin = new JButton();
jButtonLogin.setBounds(new Rectangle(320, 380, 78, 26));
jButtonLogin.setText("登录");
jButtonLogin.setUI(new BEButtonUI()
.setNormalColor(BEButtonUI.NormalColor.green));
// 回车登录
getRootPane().setDefaultButton(jButtonLogin);
// 退出
jButtonExit = new JButton();
jButtonExit.setUI(new BEButtonUI()
.setNormalColor(BEButtonUI.NormalColor.lightBlue));
jButtonExit.setBounds(new Rectangle(420, 380, 78, 26));
jButtonExit.setText("退出");
// 包含所有的元素
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(jLabelUserName, null);
jContentPane.add(jLabelPassWord, null);
jContentPane.add(jButtonLogin, null);
jContentPane.add(jButtonExit, null);
jContentPane.add(jTextFieldUserName, null);
jContentPane.add(jTextFieldPassWord, null);
getContentPane().add(jContentPane);
jTextFieldUserName.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER){
jTextFieldPassWord.requestFocus();
}
}
});
jTextFieldPassWord.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER){
username = jTextFieldUserName.getText();
password = MD5Util.string2MD5(jTextFieldPassWord.getText());
User user = new User();
user.setUsername(username);
user.setPassword(password);
String s=user.getUsername();
String p=jTextFieldPassWord.getText();
UserDao userDao = new UserDao();
int choice = 0;
if(!userDao.checkUser(user)) {
JOptionPane.showMessageDialog(null, "用户名和密码错误","消息提示",JOptionPane.WARNING_MESSAGE);
}else {
setVisible(false);
MainMenuFrame MM = new MainMenuFrame();
uname = s;
pwd=p;
}
}
}
});
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
// 添加监控
jTextFieldUserName.addActionListener(this);
jTextFieldPassWord.addActionListener(this);
jButtonLogin.addActionListener(this);
jButtonExit.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
// 获取账号和密码
username = jTextFieldUserName.getText();
password = MD5Util.string2MD5(jTextFieldPassWord.getText());
User user = new User();
user.setUsername(username);
user.setPassword(password);
String s = user.getUsername();
String p = jTextFieldPassWord.getText();
UserDao userDao = new UserDao();
int choice = 0;
if (e.getSource() == jButtonLogin) {
if (!userDao.checkUser(user)) {
JOptionPane.showMessageDialog(null, "用户名和密码错误", "消息提示", JOptionPane.WARNING_MESSAGE);
} else {
setVisible(false);
MainMenuFrame MM = new MainMenuFrame();
uname = s;
pwd = p;
}
} else if (e.getSource() == jButtonExit) {
System.exit(0);
}
}
// 测试
public static void main(String[] args) {
new LoginFrame();
}
}
package com.sjsq.view;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;
/*
* 登陆成功后主界面
*/
public class MainMenuFrame extends JFrame implements ActionListener{
private JFrame mainmenu;
private JTextArea text;
// 标题栏(关于)
private JMenuBar menuBar1;
private JMenuItem aboutSystem;
public MainMenuFrame() {
mainmenu();
}
public void mainmenu() {
mainmenu = new JFrame("极客大学学生管理系统");
setLocationRelativeTo(null);// 将容器显示在屏幕中央
mainmenu.setSize(850, 650);
mainmenu.getContentPane().add(new JScrollPane(text));
JPanel jContentPane = new JPanel();
jContentPane.setLayout(null);
// 查询学生按钮
JButton jButtonSelect = new JButton();
jButtonSelect.setBounds(new Rectangle(320, 100, 100, 52));
jButtonSelect.setText("查询学生");
jButtonSelect.setUI(new BEButtonUI()
.setNormalColor(BEButtonUI.NormalColor.lightBlue));
getRootPane().setDefaultButton(jButtonSelect);// 回车登录
// 添加学生按钮
JButton jButtonAdd = new JButton();
jButtonAdd.setUI(new BEButtonUI()
.setNormalColor(BEButtonUI.NormalColor.lightBlue));
jButtonAdd.setBounds(new Rectangle(320, 200, 100, 52));
jButtonAdd.setText("添加学生");
// 修改密码按钮
JButton jButtonAlterPwd = new JButton();
jButtonAlterPwd.setUI(new BEButtonUI()
.setNormalColor(BEButtonUI.NormalColor.lightBlue));
jButtonAlterPwd.setBounds(new Rectangle(320, 300, 100, 52));
jButtonAlterPwd.setText("密码修改");
// 退出系统按钮
JButton jButtonExit = new JButton();
jButtonExit.setUI(new BEButtonUI()
.setNormalColor(BEButtonUI.NormalColor.lightBlue));
jButtonExit.setBounds(new Rectangle(320, 400, 100, 52));
jButtonExit.setText("退出系统");
jContentPane.add(jButtonSelect, null);
jContentPane.add(jButtonAdd, null);
jContentPane.add(jButtonAlterPwd, null);
jContentPane.add(jButtonExit, null);
// 添加Label到Frame
mainmenu.getContentPane().add(jContentPane);
// 设置字体
Font font = new Font("微软雅黑",Font.BOLD,16);
// 标题栏
menuBar1 = new JMenuBar();
//aboutSystem = new JMenuItem("关于本系统",new ImageIcon("src/images/icons/about.png"));
aboutSystem = new JMenuItem("关于本系统");
aboutSystem.setMnemonic('H');
menuBar1.add(aboutSystem);
// 查询学生
jButtonSelect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("------查询学生-----");
QueryStudentInfo queryStudentInfo = new QueryStudentInfo();
}
});
// 添加学生
jButtonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("------添加学生-----");
AddStudentInfo addStudentInfo = new AddStudentInfo();
}
});
// 修改密码
jButtonAlterPwd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("------修改密码-----");
ModifyPasswordInfo modifyPasswordInfo = new ModifyPasswordInfo();
}
});
// 退出系统
jButtonExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("------退出系统-----");
System.exit(1);
}
});
// 关于系统
aboutSystem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("------关于系统------");
AboutSystem aboutSystem = new AboutSystem();
}
});
// 关闭窗口监控
mainmenu.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
System.exit(1);
}
});
mainmenu.setJMenuBar(menuBar1);
mainmenu.setVisible(true);
mainmenu.setLocation(250, 50);
aboutSystem.addActionListener(this);
}
// 主函数测试
public static void main(String[] args) {
new MainMenuFrame();
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
}
package com.sjsq.view;
import javax.swing.*;
import java.awt.*;
public class AboutSystem extends JFrame{
private JLabel jlabel1,jlabel2;
private Font font;
public AboutSystem() {
//设置容器标题
setTitle("关于本系统");
//设置容器大小
setSize(600, 450);
//将容器显示在屏幕中央
setLocationRelativeTo(null);
AboutSystem();
//点击右上角的关闭,只关闭本窗口,不影响住窗口
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
//设置窗口可见
setVisible(true);
//设置窗口大小可以改变
setResizable(true);
}
private void AboutSystem() {
//以绝对布局的方式布局
setLayout(null);
font = new Font("楷体", Font.BOLD, 20);
jlabel1 = new JLabel("联系方式");
jlabel1.setBounds(230, 50, 150, 50);
jlabel1.setFont(font);
jlabel2 = new JLabel("QQ:3079118617");
jlabel2.setBounds(230, 100, 150, 50);
jlabel2.setFont(font);
add(jlabel1);
add(jlabel2);
}
public static void main(String[] args){
new AboutSystem();
}
}
package com.sjsq.view;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;
import com.sjsq.controller.StudentController;
import com.sjsq.controller.impl.StudentControllerImpl;
import com.sjsq.dao.StudentDao;
import com.sjsq.model.Student;
@SuppressWarnings("serial")
public class QueryStudentInfo extends JFrame implements ActionListener {
private JScrollPane panel;
private JButton next, previous, first, last, query;
private JButton modifyBtn, deleteBtn, backBtn;
private JLabel studentId;
private JLabel studengName;
private JLabel studentSex;
private JLabel studentProvince;
private JTextField studentIdContent;
private JTextField studengNameContent;
private JTextField studentSexContent;
private JTextField studentProvinceContent;
private JLabel label1, label2; // 1.显示总页数和当前页数 2.每页显示数
private JTable table;
public int currentPage = 1; // 当前页
public int totalPage = 0; // 总页数
public int totalRowCount = 0; // 总行数
public int pageCount; // 每页显示数目
public int column = 0;
public int restCount; // 最后一页数目
public Object[][] resultData; // 结果集二维数组
// 声明下拉菜单数据
String[] array = {
"20", "30", "40", "50", "60" };
JComboBox box = new JComboBox(array);// 将数组array放到下拉菜单中
// JTable表信息相关变量
public List<Student> students = Student.students;
public String[] columnNames = {
"学号", "姓名", "性别", "学院", "专业", "生日", "省份", "电话", "邮箱" };
public DefaultTableModel model = null;// 默认的表格控制模型
// 窗体及表的建立
public QueryStudentInfo() {
super("学生信息查询统计");
this.setSize(1040, 680);
setLocationRelativeTo(null);// 将容器显示在屏幕中央
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);// 点击右上角的关闭,只关闭本窗口,不影响住窗口
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// 设置窗口不可以改变
setResizable(false);
JLabel queryData;
Font font = new Font("微软雅黑", Font.CENTER_BASELINE, 10);
studentId = new JLabel("学号");
studentId.setBounds(100, 30, 40, 30);
studentId.setFont(font);
studentIdContent = new JTextField();
studentIdContent.setBounds(145, 30, 100, 30);
studengName = new JLabel("学生姓名");
studengName.setBounds(270, 30, 70, 30);
studengName.setFont(font);
studengNameContent = new JTextField();
studengNameContent.setBounds(341, 30, 100, 30);
// “姓名”,“性别”,“省份”
studentProvince = new JLabel("省份");
studentProvince.setBounds(100, 65, 40, 30);
studentProvince.setFont(font);
studentProvinceContent = new JTextField();
studentProvinceContent.setBounds(145, 65, 100, 30);
studentSex = new JLabel("学生性别");
studentSex.setBounds(270, 65, 70, 30);
studentSex.setFont(font);
studentSexContent = new JTextField();
studentSexContent.setBounds(341, 65, 100, 30);
query = new JButton("查询");
query.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.lightBlue));
query.setBounds(600, 30, 95, 30);
// query.setFont(font);
query.setForeground(Color.blue);
// 设置查询图标
//ImageIcon icon1 = new ImageIcon("src/images/query2.png");
//query.setIcon(icon1);
table = new JTable();
box.setBounds(890, 105, 100, 20);
label2 = new JLabel("每页显示条数:");
label2.setBounds(800, 93, 120, 50);
panel = new JScrollPane();// 设置滚动条
panel.setViewportView(table);
panel.setBounds(42, 136, 950, 420);
first = new JButton("第一页");
first.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
first.setBounds(44, 570, 90, 30);
previous = new JButton("上一页");
previous.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
previous.setBounds(164, 570, 90, 30);
next = new JButton("下一页");
next.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
next.setBounds(284, 570, 90, 30);
last = new JButton("最后一页");
last.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
last.setBounds(404, 570, 90, 30);
/*modifyBtn = new JButton("修改");
modifyBtn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
modifyBtn.setBounds(524, 570, 90, 30);
deleteBtn = new JButton("删除");
deleteBtn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.red));
deleteBtn.setBounds(644, 570, 90, 30);
backBtn = new JButton("关闭");
backBtn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.blue));
backBtn.setBounds(764, 570, 90, 30);*/
// 新的位置
modifyBtn = new JButton("修改");
modifyBtn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
modifyBtn.setBounds(200, 570, 90, 30);
deleteBtn = new JButton("删除");
deleteBtn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.red));
deleteBtn.setBounds(400, 570, 90, 30);
backBtn = new JButton("关闭");
backBtn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.blue));
backBtn.setBounds(600, 570, 90, 30);
/* 添加监听 */
previous.addActionListener(this);
next.addActionListener(this);
first.addActionListener(this);
last.addActionListener(this);
query.addActionListener(this);
// 返回
backBtn.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
dispose();// 点击返回按钮,销毁当前窗口
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
});
// 修改
modifyBtn.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
int selectedRowIndex = 7;
selectedRowIndex = table.getSelectedRow();
if (selectedRowIndex == -1) {
JOptionPane.showMessageDialog(null, "请在表格中选中一条数据", "消息提示", JOptionPane.WARNING_MESSAGE);
} else {
String sid = table.getValueAt(selectedRowIndex, 0).toString();
String sname = table.getValueAt(selectedRowIndex, 1).toString();
String ssex = table.getValueAt(selectedRowIndex, 2).toString();
String scollege = table.getValueAt(selectedRowIndex, 3).toString();
String smajor = table.getValueAt(selectedRowIndex, 4).toString();
String sbirthday = table.getValueAt(selectedRowIndex, 5).toString();
String sprovince = table.getValueAt(selectedRowIndex, 6).toString();
String sphone = table.getValueAt(selectedRowIndex, 7).toString();
String semail = table.getValueAt(selectedRowIndex, 8).toString();
EditStudentInfo editStudentInfo = new EditStudentInfo(sid, sname, ssex, scollege, smajor, sbirthday,
sprovince, sphone, semail);
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
});
deleteBtn.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("------用户点击按钮------");
int selectedRowIndex = 7;
selectedRowIndex = table.getSelectedRow();
if (selectedRowIndex == -1) {
JOptionPane.showMessageDialog(null, "请在表格中选中一条数据", "消息提示", JOptionPane.WARNING_MESSAGE);
} else {
String sid = table.getValueAt(selectedRowIndex, 0).toString();
StudentController studentController = new StudentControllerImpl();
boolean flag = studentController.deleteStudentController(sid);
if (flag) {
JOptionPane.showMessageDialog(null, "删除学生信息成功", "消息提示", JOptionPane.QUESTION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "删除学生信息失败", "消息提示", JOptionPane.WARNING_MESSAGE);
}
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
});
label1 = new JLabel();
label1.setBounds(420, 400, 180, 60);
this.getContentPane().setLayout(null);
// 获取内容面板,再对其加入组件,显示多少页
// this.getContentPane().add(box);
// 显示分页条数
//this.getContentPane().add(label2);
// 滚动条
this.getContentPane().add(panel);
// 分页
//this.getContentPane().add(previous);
//this.getContentPane().add(next);
//this.getContentPane().add(first);
//this.getContentPane().add(last);
this.getContentPane().add(label1);
this.getContentPane().add(studentId);
this.getContentPane().add(studentIdContent);
this.getContentPane().add(studengName);
this.getContentPane().add(studengNameContent);
//this.getContentPane().add(studentSex);
//this.getContentPane().add(studentSexContent);
//this.getContentPane().add(studentProvince);
//this.getContentPane().add(studentProvinceContent);
this.getContentPane().add(modifyBtn);
this.getContentPane().add(deleteBtn);
this.getContentPane().add(backBtn);
this.getContentPane().add(query);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
/* 从MySQL数据库中获取数据 */
try {
StudentDao commoditySaleDetailDao = new StudentDao();
ResultSet rs = commoditySaleDetailDao.queryAll();
ResultSetMetaData metaData;
metaData = rs.getMetaData();
int number = metaData.getColumnCount();
while (rs.next()) {
String sId = rs.getString(1);
String sName = rs.getString(2);
String sSex = rs.getString(3);
String sCollege = rs.getString(4);
String sMajor = rs.getString(5);
String sBirthday = rs.getString(6);
String sProvince = rs.getString(7);
String sPhone = rs.getString(8);
String sEmail = rs.getString(9);
Student s = new Student(sId, sName, sSex, sCollege, sMajor, sBirthday, sProvince, sPhone, sEmail);
Student.students.add(s);
}
} catch (SQLException ex) {
String[] options3 = {
"新建MyTable数据表", "取消" };
int strength3 = JOptionPane.showOptionDialog(null, "表MyTable不存在!", "信息", JOptionPane.YES_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, options3, options3[0]);
if (strength3 == javax.swing.JOptionPane.YES_OPTION) {
System.out.println("The Table not exsits.");
}
if (strength3 == javax.swing.JOptionPane.INFORMATION_MESSAGE) {
System.exit(0);
}
}
/**
* 事件监听
*/
/* 下拉菜单事件监听 */
box.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String Str = (String) box.getSelectedItem();
pageCount = Integer.parseInt(Str);
initTable();
System.out.println(pageCount);
}
});
}
/**
* 获取下一页
*/
public int getNextPage() {
if (this.currentPage != this.totalPage) {
return ++currentPage;
}
return -1;
}
/**
* 获取上一页
*/
public int getPreviousPage() {
if (this.currentPage != 1) {
return --currentPage;
}
return -1;
}
/**
* 获取最后一页
*/
public int getLastPage() {
currentPage = totalPage;
return currentPage;
}
/**
* 获取第一页
*/
public int getFirstPage() {
currentPage = 1;
return currentPage;
}
/**
* 获取总页数
*
*
*/
public int getTotolPage() {
return this.totalPage;
}
/**
* 获取当前页
*/
public int getCurrentPage() {
return this.currentPage;
}
/**
* 获得原始数据集
*
* @param students
* @return String sId, String sName, String sSex, String sBirthday, String
* sProvince, String sHobby, String sPhone
*/
public Object[][] getData(List<Student> students) {
if (students.size() > 0) {
Object[][] data = new Object[students.size()][4];
for (int i = 0; i < students.size(); i++) {
Student s = students.get(i);
// 把List**的数据赋给Object数组
Object[] a = {
s.getsId(), s.getsName(), s.getsSex(), s.getsCollege(), s.getsMajor(), s.getsBirthday(),
s.getsProvince(), s.getsPhone(), s.getsEmail() };
// 把数组的值赋给二维数组的一行
data[i] = a;
}
return data;
}
return null;
}
/**
* 初始化结果集
*
* @param data
*/
public void initResultData(Object[][] data) {
if (data != null) {
String Str = (String) box.getSelectedItem();
pageCount = Integer.parseInt(Str);
resultData = data;// 总的结果集
column = data[0].length;// 表的列数
totalRowCount = data.length;// 表的长度
totalPage = totalRowCount % pageCount == 0 ? totalRowCount / pageCount : totalRowCount / pageCount + 1;// 结果集的总页数
restCount = totalRowCount % pageCount == 0 ? pageCount : totalRowCount % pageCount;// 最后一页的数据数
label1.setText("总共" + totalRowCount + "记录|当前第" + currentPage + "页");
} else {
restCount = 0;
}
}
/**
* 获取分页数据
*
* @return
*/
public Object[][] getPageData() {
Object[][] currentPageData = new Object[pageCount][column];// 构造每页数据集
if (this.getCurrentPage() < this.totalPage) {
// 如果当前页数小于总页数,那么每页数目应该是规定的数pageCount
for (int i = pageCount * (this.getCurrentPage() - 1); i < pageCount * (this.getCurrentPage() - 1)
+ pageCount; i++) {
for (int j = 0; j < column; j++) {
// 把结果集中对应每页的每一行数据全部赋值给当前页的每一行的每一列
currentPageData[i % pageCount][j] = resultData[i][j];
}
}
} else {
// 在动态改变数据结果集的时候,如果当前页没有数据了,则回到前一页(一般针对最后一页而言)
if (pageCount * (this.getCurrentPage() - 1) >= totalRowCount)
this.currentPage--;
for (int i = pageCount * (this.getCurrentPage() - 1); i < pageCount * (this.getCurrentPage() - 1)
+ restCount; i++) {
for (int j = 0; j < column; j++) {
currentPageData[i % pageCount][j] = resultData[i][j];
}
}
}
return currentPageData;
}
/**
* 初始化表格数据
*/
public void initTable() {
Object[][] data = getData(students);
if (data != null) {
initResultData(data);
model = new DefaultTableModel(getPageData(), columnNames);
} else {
// 如果结果集中没有数据,那么就用空来代替数据集中的每一行
initResultData(data);
Object[][] nothing = {
{
}, {
}, {
}, {
}, {
} };
model = new DefaultTableModel(nothing, columnNames);
totalRowCount = 0;
}
table.setModel(model);
table.setRowHeight(20);
DefaultTableCellRenderer r = new DefaultTableCellRenderer();
r.setHorizontalAlignment(JLabel.CENTER);
table.setDefaultRenderer(Object.class, r);
}
/**
* 按钮事件
*/
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// String ItemName = e.getActionCommand();
String[] data = new String[4];
JButton button = (JButton) e.getSource();
if (button.equals(first)) {
int i = getFirstPage();
if (i == -1)
return;
}
if (button.equals(previous)) {
int i = getPreviousPage();
if (i == -1)
return;
}
if (button.equals(next)) {
int i = getNextPage();
if (i == -1)
return;
}
if (button.equals(last)) {
int i = getLastPage();
if (i == -1)
return;
}
if (button.equals(modifyBtn)) {
}
if (button.equals(deleteBtn)) {
}
if (button.equals(backBtn)) {
dispose();// 点击返回按钮,销毁当前窗口
}
if (button.equals(query)) {
data[0] = studentIdContent.getText();
data[1] = studengNameContent.getText();
data[2] = studentProvinceContent.getText();
data[3] = studentSexContent.getText();
StudentController studentController = new StudentControllerImpl();
ResultSet rs = null;
rs = studentController.queryByCondition(data);
if (rs == null) {
JOptionPane.showMessageDialog(null, "依据该条件没有查询到相应的信息", "消息提示", JOptionPane.WARNING_MESSAGE);
initTable();
} else {
try {
ResultSetMetaData metaData;
metaData = rs.getMetaData();
int number = metaData.getColumnCount();
students.clear();
while (rs.next()) {
String sId = rs.getString(1);
String sName = rs.getString(2);
String sSex = rs.getString(3);
String sCollege = rs.getString(4);
String sMajor = rs.getString(5);
String sBirthday = rs.getString(6);
String sProvince = rs.getString(7);
String sPhone = rs.getString(8);
String sEmail = rs.getString(9);
Student s = new Student(sId, sName, sSex, sCollege, sMajor, sBirthday, sProvince, sPhone,
sEmail);
Student.students.add(s);
}
} catch (SQLException ex) {
String[] options3 = {
"新建MyTable数据表", "取消" };
int strength3 = JOptionPane.showOptionDialog(null, "表MyTable不存在!", "信息", JOptionPane.YES_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, options3, options3[0]);
if (strength3 == javax.swing.JOptionPane.YES_OPTION) {
System.out.println("The Table not exsits.");
}
if (strength3 == javax.swing.JOptionPane.INFORMATION_MESSAGE) {
System.exit(0);
}
}
initTable();
}
}
Object[][] currentPageData = new Object[pageCount][column];// 构造每页数据集
if (this.getCurrentPage() == 1) {
for (int i = pageCount * (this.getCurrentPage() - 1); i < pageCount * (this.getCurrentPage() - 1)
+ restCount; i++) {
for (int j = 0; j < column; j++) {
currentPageData[i % pageCount][j] = resultData[i][j];
}
}
} else {
if (this.getCurrentPage() < this.totalPage) {
// 如果当前页数小于总页数,那么每页数目应该是规定的数pageCount
for (int i = pageCount * (this.getCurrentPage() - 1); i < pageCount * (this.getCurrentPage() - 1)
+ pageCount; i++) {
for (int j = 0; j < column; j++) {
// 把结果集中对应每页的每一行数据全部赋值给当前页的每一行的每一列
currentPageData[i % pageCount][j] = resultData[i][j];
}
}
} else {
// 在动态改变数据结果集的时候,如果当前页没有数据了,则回到前一页(一般针对最后一页而言)
System.out.println(this.getCurrentPage());
if (pageCount * (this.getCurrentPage() - 1) >= totalRowCount)
this.currentPage--;
for (int i = pageCount * (this.getCurrentPage() - 1); i < pageCount * (this.getCurrentPage() - 1)
+ restCount; i++) {
for (int j = 0; j < column; j++) {
currentPageData[i % pageCount][j] = resultData[i][j];
}
}
}
}
DefaultTableModel model = new DefaultTableModel(currentPageData, columnNames);
table.setModel(model);
label1.setText("总共" + totalRowCount + "记录|当前第" + currentPage + "页");
}
// 测试
public static void main(String[] args) {
QueryStudentInfo q = new QueryStudentInfo();
}
}
Java+Swing实现仓库管理系统
Java+Swing实现学生宿舍管理系统
Java+Swing实现学生选课管理系统
请联系QQ:3079118617
若此文章侵犯您的权益,请通知我删除,谢谢。
奋斗就是刚开始很难,然后慢慢很容易。堕落就是刚开始很容易,然后慢慢很难。为了梦想,冲啊!