图书管理系统在生活和学校中是最为常见的,这学期的java课程设计题目中的其中一个就是实现图书管理系统,
做完课设后,在此记录下。
我的图书管理系统一共分为几个模块。图书查询模块,管理员模块(默认只有一个管理员),读者模块。
图书管理系统结构图如下所示:
1、管理员模块
管理员模块中一共包含三个部分,其一是管理员登录(此系统默认只有一个管理员),其二是图书入库管理,其三是用户借阅信息管理。
主窗口程序代码如下:主要执行查询操作和显示查询结果:
package per.tushu.frame;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import per.tushu.storage.FindBook;
public class MainFrame extends JFrame{
JLabel label1,label2,info;
JPanel jpanel,jp1,jp2,jp3;
JTextField text;
JButton button,admin,stu;
JButton lend;
DefaultTableModel tableModel;
public MainFrame(){
this.setLayout(new BorderLayout());
this.setBounds(400, 200, 600, 450);
this.setTitle("图书查询");
//窗体最上面的部分
label1 = new JLabel("图书查询",SwingConstants.CENTER);
label1.setFont(new Font("楷体",Font.BOLD,40)); //设置字体和大小
//窗体中间的部分
label2 = new JLabel("书名:");
text = new JTextField(15);
button = new JButton("查询");
jpanel = new JPanel();
jpanel.setLayout(new BorderLayout());
jp1 = new JPanel();
jp2 = new JPanel(); //窗体最下面的部分(及显示查询内容的地方)
// jp2.setBackground(Color.BLUE);
stu = new JButton("用户登录");
admin = new JButton("管理员");
// //测试
// lend = new JButton("确认借阅");
jp1.add(label2);
jp1.add(text);
jp1.add(button);
// jp1.add(lend);
jp3 = new JPanel();
jp2.setLayout(new BorderLayout());
jp3.setLayout(new FlowLayout(FlowLayout.RIGHT));
jp3.add(stu);
jp3.add(admin);
jp2.add(jp3,BorderLayout.SOUTH);
// jp2.add(info,BorderLayout.SOUTH);
jpanel.add(jp1,BorderLayout.NORTH);
jpanel.add(jp2);
this.add(label1,BorderLayout.NORTH);
this.add(jpanel);
MyEvent();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void MyEvent(){
// 查询按钮事件
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
new FindBook().findInfo(jp2,text);
}
});
// 管理员按钮事件
admin.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
new LoginFrame().show();
}
});
//用户按钮事件
stu.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
new UserLoginFrame().show();
}
});
}
public static void main(String[] args){
new MainFrame();
}
}
主窗口显示效果如下:
管理员登录:默认管理员账号为admin,若密码输入错误则有提示信息,密码正确则进入管理员管理界面。完整代码如下:
package per.tushu.frame;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
// 管理员登录模块
public class LoginFrame extends JFrame{
JLabel label,name,pass;
JButton login;
JTextField adminName;
JPasswordField password;
JPanel panel,jp1,jp2;
public LoginFrame(){
this.setBounds(400, 200, 300, 200);
this.setTitle("图书馆管理系统登录");
this.setLayout(new BorderLayout());
label = new JLabel("登录",SwingConstants.CENTER);
label.setFont(new Font("楷体",Font.BOLD,30));
name = new JLabel("账 号");
pass = new JLabel("密 码");
adminName = new JTextField(12);
adminName.setText("admin");
adminName.setHorizontalAlignment(SwingConstants.CENTER);
password = new JPasswordField(12);
password.setHorizontalAlignment(SwingConstants.CENTER);
password.setEchoChar('*'); //设置回显字符
panel = new JPanel();
jp1 = new JPanel();
jp2 = new JPanel();
panel.setLayout(new BorderLayout());
jp1.add(adminName);
jp1.add(name);
jp1.add(password);
jp1.add(pass);
panel.add(jp1);
login = new JButton("登录");
jp2.add(login);
panel.add(jp2,BorderLayout.SOUTH);
this.add(label,BorderLayout.NORTH);
this.add(panel);
MyEvent();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void MyEvent(){
login.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String word = "123456"; // 正确密码
String str = new String(password.getPassword());
if(str.equals(word))
new LendAdminFrame().show();
// new TableFrame().show();
// new RuKuFrame();
else{
String str1 = "你输入的密码不正确,原因可能是:\n" + "1、忘记密码;\n" + "2、未开启小键盘;\n" + "3、大小写未区分。";
JOptionPane.showMessageDialog(null, str1);
// new LoginErrorFrame().show();
}
LoginFrame.this.dispose();
}
});
}
public static void main(String[] args){
new LoginFrame();
}
}
代码执行后显示如下:
密码错误时:
图书入库管理:管理员在此界面内对图书信息进行管理。包括图书在馆内的图书号、图书名、撰写此书的作者、书的种类(可以是专业分类)、出版社、入库日期、借阅状态以及分布的校区(或分馆)。
用户借阅信息管理:管理员在此界面可以对用户的借阅信息进行管理。包括借阅者账号(默认为姓名)、所借图书编号、书名以及借书日期。此表会根据用户借阅图书以及归还图书动态变化。
图书入库管理和用户借阅信息管理的功能我用了一个类来实现。不过由另外一个类写了两个按钮,来保证究竟要哪一个功能起作用。用于管理这两个小模块的代码如下:package per.tushu.frame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LendAdminFrame extends JFrame{
JPanel panel;
JButton storage,lendInfo;
public LendAdminFrame(){
this.setTitle("管理员");
this.setBounds(400,300,200,200);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
storage = new JButton("图书入库管理");
lendInfo = new JButton("借阅信息管理");
this.add(storage);
this.add(lendInfo);
MyEvent();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void MyEvent(){
// 图书入库管理
storage.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
new TableFrame(storage.getText()).show();
}
});
// 用户借阅信息管理
lendInfo.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
new TableFrame(lendInfo.getText()).show();
}
});
}
public static void main(String[] args){
new LendAdminFrame();
}
}
代码显示效果如下:
两个小模块实现功能的代码如下:package per.tushu.frame;
import java.awt.BorderLayout;
import java.awt.CheckboxGroup;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import per.tushu.storage.PutinStorage;
public class TableFrame extends JFrame{
DefaultTableModel tableModel;
Vector vector;
JMenuBar menuBar;
JButton add,del,exit,find,save;
JTable table;
JPanel panelUP,panelDown; //增加信息的面板
// 内部类中的变量
JLabel[] label;
// JLabel idLabel,titleLabel,authorLabel,typeLable,pressLable,storageTimeLabel,stateLabel,campuNameLabel;
JComboBox typeBox,pressBox;
JCheckBox campuNameCheck1,campuNameCheck2;
JRadioButton stateRadio1,stateRadio2;
JTextField idText,titleText,authorText;
CheckboxGroup cg;
ButtonGroup bg;
JLabel year,mon,day;
JComboBox yearText,monText,dayText;
JPanel panel,panelSouth;
JButton button;
String[] str=null;
JPanel[] panelLeft,panelRight;
private String database = "bookstorage";
// private String database = "haha";
private String tablesName;
public TableFrame(String title){
// tablesName = tableName;
this.setBounds(300, 200, 600, 450);
this.setTitle(title);
this.setLayout(new BorderLayout());
add = new JButton("增加");
del = new JButton("删除");
save = new JButton("保存");
find = new JButton("查找");
exit = new JButton("退出");
panelUP = new JPanel();
panelUP.setLayout(new FlowLayout(FlowLayout.LEFT));
panelUP.add(add);
panelUP.add(del);
panelUP.add(save);
panelUP.add(find);
panelUP.add(exit);
Vector rowData = null;
Vector columnNames = null;
if(title.equals("图书入库管理")){
rowData = PutinStorage.getRows("books");
columnNames = PutinStorage.getHead("books");
}else{
rowData = PutinStorage.getRows("lendInfo");
columnNames = PutinStorage.getHead("lendInfo");
}
/* for(int i = 0; i < columnNames.size(); i++)
System.out.println(columnNames.get(i));*/
// 新建表格
tableModel = new DefaultTableModel(rowData,columnNames);
table = new JTable(tableModel);
// for(int i = 0; i < columnNames.size(); i++){
// int [] aa = {3,4,6};
// for(int i = 0; i < aa.length; i++){
// int t = aa[i];
// TableColumn tableColumn = table.getColumnModel().getColumn(3);
// tableColumn.setCellRenderer(new MyRender());
// tableColumn.setCellEditor(new MyEditor());
// }
table.setRowHeight(22);
JScrollPane s = new JScrollPane(table);
this.add(panelUP,BorderLayout.NORTH);
this.add(s);
MyEvent();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// 添加单元格的内部类
class AddFrame extends JFrame{
public AddFrame(){
this.setBounds(300,200,500,350);
// this.setLayout(new GridLayout(8,2));
panel = new JPanel();
panel.setLayout(new GridLayout(8,2));
panelSouth = new JPanel();
panelSouth.setLayout(new FlowLayout(FlowLayout.CENTER));
button = new JButton("OK");
panelSouth.add(button);
label = new JLabel[8];
label[0] = new JLabel("图书编号:");
label[1] = new JLabel("图书名称:");
label[2] = new JLabel("图书作者:");
label[3] = new JLabel("图书类型:");
label[4] = new JLabel("出版社:");
label[5] = new JLabel("入库时间:");
label[6] = new JLabel("借阅状态:");
label[7] = new JLabel("所在校区:");
idText = new JTextField(10);
titleText = new JTextField(10);
authorText = new JTextField(10);
String[] types = {"计算机","英语","电气","机械","材料"};
String[] press = {"人民邮电出版社","中国铁道出版社","清华大学出版社","工业出版社","电子工业出版社"};
// 年集合(实现动态添加)
ArrayList yearArray = new ArrayList();
// 获取系统时间
String time = new SimpleDateFormat("yyyy-mm-dd").format(new Date());
String contentYear = time.split("-")[0];
for(int i = 2000; i <= Integer.parseInt(contentYear); i++)
yearArray.add(String.valueOf(i));
String[] years = new String[yearArray.size()];
for(int i = 0; i < yearArray.size(); i++)
years[i] = yearArray.get(i);
String[] month = {"1","2","3","4","5","6","7","8","9","10","11","12"};
String[] days = {"1","2","3","4","5","6","7","8","9","10",
"11","12","13","14","15","16","17","18","19","20",
"21","22","23","24","25","26","27","28","29","30"};
/* ArrayList> valueDay = new ArrayList>();
ArrayList value;
for(int i = 0; i < 12; i++){
if(i == 1){
value = new ArrayList();
for(int j = 0; j < 29; j++)
value.add(String.valueOf(j + 1));
}
else if(i == 0 || i == 2 || i == 4 || i == 6 || i == 7 || i == 9 || i == 11){
value = new ArrayList();
for(int j = 0; j < 31; j++)
value.add(String.valueOf(j + 1));
}
else{
value = new ArrayList();
for(int j = 0; j < 30; j++)
value.add(String.valueOf(j + 1));
}
valueDay.add(value);
}
String[] days = null;
for(int i = 0; i < month.length; i++){
days = new String[valueDay.get(i).size()];
for(int j = 0; j < valueDay.get(i).size(); j++){
days[j] = valueDay.get(i).get(j);
}
}*/
typeBox = new JComboBox(types);
pressBox = new JComboBox(press);
campuNameCheck1 = new JCheckBox("A");
campuNameCheck2 = new JCheckBox("B");
cg = new CheckboxGroup();
stateRadio1 = new JRadioButton("借出");
stateRadio2 = new JRadioButton("未借");
bg = new ButtonGroup();
bg.add(stateRadio1);
bg.add(stateRadio2);
year = new JLabel("年");
mon = new JLabel("月");
day = new JLabel("日");
yearText = new JComboBox(years);
monText = new JComboBox(month);
dayText = new JComboBox(days);
panelRight = new JPanel[8];
panelLeft = new JPanel[8];
for(int i = 0; i < panelRight.length; i++){
panelRight[i] = new JPanel();
panelRight[i].setLayout(new FlowLayout(FlowLayout.LEFT));
}
for(int i = 0; i < panelLeft.length; i++){
panelLeft[i] = new JPanel();
panelLeft[i].setLayout(new FlowLayout(FlowLayout.RIGHT));
}
for(int i = 0; i < panelLeft.length; i++)
for(int j = i; j < label.length; j++)
panelLeft[i].add(label[j]);
panelRight[0].add(idText);
panelRight[1].add(titleText);
panelRight[2].add(authorText);
panelRight[3].add(typeBox);
panelRight[4].add(pressBox);
panelRight[5].add(yearText);
panelRight[5].add(year);
panelRight[5].add(monText);
panelRight[5].add(mon);
panelRight[5].add(dayText);
panelRight[5].add(day);
panelRight[6].add(stateRadio1);
panelRight[6].add(stateRadio2);
panelRight[7].add(campuNameCheck1);
panelRight[7].add(campuNameCheck2);
panel.add(panelLeft[0]);
panel.add(panelRight[0]);
panel.add(panelLeft[1]);
panel.add(panelRight[1]);
panel.add(panelLeft[2]);
panel.add(panelRight[2]);
panel.add(panelLeft[3]);
panel.add(panelRight[3]);
panel.add(panelLeft[4]);
panel.add(panelRight[4]);
panel.add(panelLeft[5]);
panel.add(panelRight[5]);
panel.add(panelLeft[6]);
panel.add(panelRight[6]);
panel.add(panelLeft[7]);
panel.add(panelRight[7]);
this.add(panelSouth,BorderLayout.SOUTH);
this.add(panel);
MyEvent();
// this.setVisible(true);
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void MyEvent(){
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String str1 = idText.getText();
String str2 = titleText.getText();
String str3 = authorText.getText();
String str4 = typeBox.getSelectedItem().toString();
String str5 = pressBox.getSelectedItem().toString();
String str6 = yearText.getSelectedItem().toString();
String str7 = monText.getSelectedItem().toString();
String str8 = dayText.getSelectedItem().toString();
String str9 = null;
String first = null,second = null;
String cam;
if(stateRadio1.isSelected())
str9 = stateRadio1.getText();
else if(stateRadio2.isSelected())
str9 = stateRadio2.getText();
if(campuNameCheck1.isSelected())
first = campuNameCheck1.getText();
if(campuNameCheck2.isSelected())
second = campuNameCheck2.getText();
// String cam = first + ","+second;
if(first == null && second != null)
cam = second;
else if(first != null && second == null)
cam = first;
else
cam = first + "," + second;
String date = str6 + "-" + str7 + "-" + str8;
String[] str = {str1,str2,str3,str4,str5,date,str9,cam};
vector = new Vector();
vector.add(str1);
vector.add(str2);
vector.add(str3);
vector.add(str4);
vector.add(str5);
vector.add(date);
vector.add(str9);
vector.add(cam);
// for(int i = 0; i < vector.size(); i++)
// System.out.println(vector.get(i).toString());
int rowNum = table.getSelectedRow();
if(rowNum == -1){
String aa1 = str1.substring(0,1);
String aa = str1.substring(1, str1.length());
long bb = Long.parseLong(aa) + 1;
String cc = aa1 + String.valueOf(bb);
tableModel.addRow(vector);
//加入表格后清除源数据
idText.setText(cc);
titleText.setText("");
authorText.setText("");
}
// Vector[][] mData = new Vector[table.getRowCount()][table.getColumnCount()];
if(rowNum != -1){
String aa = table.getValueAt(rowNum, 0).toString();
String aa1 = aa.substring(0, 1);
tableModel.insertRow(rowNum + 1, vector);
for(int i = rowNum + 2; i < table.getRowCount(); i++){
if(table.getValueAt(i, 0).toString().startsWith(aa1)){
String ee = table.getValueAt(i, 0).toString();
String ee1 = aa1 + String.valueOf(Long.parseLong(ee.substring(1, ee.length())) + 1);
table.setValueAt(ee1, i, 0);
}
}
}
}
});
}
}
public void MyEvent(){
// 增加
add.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// 增加一行空白区域
// tableModel.addRow(new Vector());
new AddFrame().show();
int rowNum = table.getSelectedRow();
if(rowNum != -1){
String aa = table.getValueAt(rowNum, 0).toString();
String aa1 = aa.substring(0, 1);
String aa2 = aa.substring(1, aa.length());
long bb = Long.parseLong(aa2) + 1;
String cc = aa1 + String.valueOf(bb);
idText.setText(cc);
}
}
});
// 删除
del.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
// 按照从下到上逐行删除(需添加鼠标事件)
int rowcount = table.getSelectedRow();
// System.out.println(rowcount);
if(rowcount >= 0){
tableModel.removeRow(rowcount);
String aa = table.getValueAt(rowcount, 0).toString().substring(0, 1);
for(int i = rowcount; i < table.getRowCount(); i++){
if(table.getValueAt(i, 0).toString().startsWith(aa)){
String ee = table.getValueAt(i, 0).toString();
String ee1 = aa + String.valueOf(Long.parseLong(ee.substring(1, ee.length())) - 1);
table.setValueAt(ee1, i, 0);
}
}
}
// table.revalidate();
}
});
// 保存
save.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
new PutinStorage().saveData(table);
}
});
// 查找
find.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
// 退出
exit.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
}
public static void main(String[] args){
new TableFrame("图书入库管理");
}
}
图书入库显示效果如下所示:
图书添加操作:
借阅信息管理显示如下:
2、图书查询模块
图书查询分为两个部分,一个是查询全部(查询框无内容时),另一个是按照关键字查询。
查询全部:查询框无查询内容时直接点击查询按钮,则会显示数据库中所有的图书数据。
按照关键字查询:查询框中有关键字时,则会显示与关键字相关的图书数据。
此模块用一个类来实现,需要连接数据库,由主页面的查询按钮控制代码如下:package per.tushu.storage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class FindBook {
Vector tableName;
// 拿到数据库中所有表的名字并储存到集合中
private Vector getTableName(){
tableName = new Vector();
Connection conn;
PreparedStatement preparedStatement;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstorage","root","123456");
// if(!conn.isClosed())
// System.out.println("成功打开数据库");
String sql = "show tables";
preparedStatement = conn.prepareStatement(sql);
ResultSet result = preparedStatement.executeQuery();
ResultSetMetaData metaData = result.getMetaData();
while(result.next()){
for(int i = 1; i <= metaData.getColumnCount(); i++){
tableName.addElement(result.getString(i));
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动");
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库");
e.printStackTrace();
}
return tableName;
}
// 构造函数
public FindBook(){}
// 拿到要查询的信息并输出到主界面
public void findInfo(JPanel panel,JTextField text){
/* for(int i = 0; i < names.size(); i++)
System.out.println(names.get(i));*/
ArrayList> datas = new ArrayList>(); // 数据库中所有的图书信息
ArrayList> outputDatas = new ArrayList>(); // 记录需要输出的信息(中间量)
ArrayList> bookN = new ArrayList>(); // 所有可借书籍的信息(在记录可借书的ID号时用到,属中间量)
ArrayList> outputBook = new ArrayList>(); //记录所有可借书籍的ID号
ArrayList lendBooks = new ArrayList(); //存储所有书籍的名称
// Vector headers = null;
Connection conn;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstorage","root","123456");
// if(!conn.isClosed())
// System.out.println("成功打开数据库");
String sql = "select * from books";
preparedStatement = conn.prepareStatement(sql);
ResultSet result = preparedStatement.executeQuery();
while(result.next()){
ArrayList al = new ArrayList();
ArrayList al2 = new ArrayList();
al.add(result.getString("title"));
al.add(result.getString("author"));
al.add(result.getString("state"));
//
if(result.getString("state").equals("未借")){
al2.add(result.getString("id"));
al2.add(result.getString("title"));
al2.add(result.getString("state"));
bookN.add(al2);
}
datas.add(al);
// System.out.println(result);
// System.out.println(result.getString("title") + "\t" + result.getString("author") + "\t" +result.getString("press"));
}
// headers = new Vector();
// ResultSetMetaData rsmd = result.getMetaData();
// for(int k = 1; k <= rsmd.getColumnCount(); k++)
// headers.addElement(rsmd.getColumnName(k));
// String[] head = new String[datas.get(0).size()];
/* System.out.println(datas.get(0).size());
for(int i = 0; i < headers.size(); i++){
System.out.println(headers.get(i).toString());
// head[i] = headers.get(i).toString();
} */
// 存储所有书籍的名称(不重复),以备后用
for(int i = 0; i < datas.size(); i++)
if(!lendBooks.contains(datas.get(i).get(0)))
lendBooks.add(datas.get(i).get(0));
/* for(int i = 0; i < lendBooks.size(); i++)
System.out.println(lendBooks.get(i));*/
// 按要求输出内容
String findName = text.getText();
if(findName.equals("")){
int row = datas.size();
int columns = datas.get(0).size();
Object[][] demo = new Object[row][columns + 1];
for(int i = 0; i < row;i++){
if(!outputDatas.contains(datas.get(i)) && datas.get(i).get(2).equals("未借"))
outputDatas.add(datas.get(i));
}
Vector counter = new Vector();
// System.out.println("size========"+outputDatas.size());
for(int i = 0; i < outputDatas.size(); i++){
int count = 0;
for(int j = 0; j < datas.size(); j++){
if(datas.get(j).equals(outputDatas.get(i)))
count ++;
}
counter.add(count);
}
// System.out.println("counter========"+counter.size());
// // 输出同一本图书状态为“未借”的数量
// for(int i = 0; i < counter.size(); i++)
// System.out.println(counter.get(i));
// //尝试输出没有重复项的图书库
// for(int i = 0; i < outputDatas.size(); i++){
// for(int j = 0; j < outputDatas.get(0).size(); j++)
// System.out.print(outputDatas.get(i).get(j));
// System.out.println();
// }
// System.out.println(counter.size() + "===========" + outputDatas.size());
for(int i = 0; i < outputDatas.size(); i++){
ArrayList mid = new ArrayList();
mid.add(outputDatas.get(i).get(0));
for(int j = 0; j < bookN.size(); j++){
if(bookN.get(j).get(1).equals(outputDatas.get(i).get(0))){
mid.add(bookN.get(j).get(0));
}
}
outputBook.add(mid);
}
/*for(int i = 0; i < outputBook.size(); i++){
for(int j = 0; j < outputBook.get(i).size(); j++)
System.out.print(outputBook.get(i).get(j) + "\t");
System.out.println();
}
*/
String[][] books = new String[outputBook.size()][2];
for(int i = 0; i < outputBook.size(); i++){
books[i][0] = outputBook.get(i).get(0);
books[i][1] = "";
for(int j = 1; j < outputBook.get(i).size(); j++){
if(j < outputBook.get(i).size() - 1)
books[i][1] = books[i][1] + outputBook.get(i).get(j) + "、" ;
else if(j == outputBook.get(i).size() - 1)
books[i][1] = books[i][1] + outputBook.get(i).get(j);
}
}
/* for(int i = 0; i < books.length; i++){
for(int j = 0; j < 2; j++)
System.out.print(books[i][j] + "\t");
System.out.println();
}*/
for(int i = 0; i < outputDatas.size(); i++)
for(int j = 0; j < outputDatas.get(0).size(); j++){
demo[i][0] = books[i][1];
if(j == 2)
demo[i][3] = counter.get(i) + "本可借";
else
demo[i][j + 1] = outputDatas.get(i).get(j);
}
// System.out.println(outputDatas.size());
String[] head = {"可借编号","书名","作者","借阅状态"};
DefaultTableModel tableModel = new DefaultTableModel(demo,head);
JTable table = new JTable(tableModel);
JScrollPane scroll = new JScrollPane(table);
panel.add(scroll);
panel.revalidate();
}else{
// System.out.println(datas.get(0).get(0));
// for(int i = 0; i < datas.size(); i++){
// for(int j = 0; j < datas.get(i).size(); j++){
// if(datas.get(i).get(j).contains(findName)){
// outputDatas.add(datas.get(i));
// // System.out.print(datas.get(i));
// }
//
// // System.out.print(datas.get(i).get(j) + "\t");
// }
// // System.out.println();
// }
for(int i = 0; i < datas.size();i++){
if(!outputDatas.contains(datas.get(i)) && datas.get(i).get(2).equals("未借") && datas.get(i).get(0).contains(findName))
outputDatas.add(datas.get(i));
}
if(outputDatas.isEmpty())
System.out.println("查找内容不存在");
else{
int row = outputDatas.size();
int columns = outputDatas.get(0).size();
Object[][] demo = new Object[row][columns + 1];
/* for(int i = 0; i < outputDatas.size(); i++){
for(int j = 0; j < outputDatas.get(0).size(); j++){
System.out.print(outputDatas.get(i).get(j) + "\t");
}
System.out.println();
}*/
Vector counter = new Vector();
// System.out.println("size========"+outputDatas.size());
for(int i = 0; i < outputDatas.size(); i++){
int count = 0;
for(int j = 0; j < datas.size(); j++){
if(datas.get(j).equals(outputDatas.get(i)))
count ++;
}
counter.add(count);
}
// for(int i = 0; i < counter.size(); i++)
// System.out.println(counter.get(i));
for(int i = 0; i < outputDatas.size(); i++){
ArrayList mid = new ArrayList();
mid.add(outputDatas.get(i).get(0));
for(int j = 0; j < bookN.size(); j++){
if(bookN.get(j).get(1).equals(outputDatas.get(i).get(0))){
mid.add(bookN.get(j).get(0));
}
}
outputBook.add(mid);
}
String[][] books = new String[outputBook.size()][2];
for(int i = 0; i < outputBook.size(); i++){
books[i][0] = outputBook.get(i).get(0);
books[i][1] = "";
for(int j = 1; j < outputBook.get(i).size(); j++){
if(j < outputBook.get(i).size() - 1)
books[i][1] = books[i][1] + outputBook.get(i).get(j) + "、" ;
else if(j == outputBook.get(i).size() - 1)
books[i][1] = books[i][1] + outputBook.get(i).get(j);
}
}
/* for(int i = 0; i < books.length; i++){
for(int j = 0; j < 2; j++)
System.out.print(books[i][j] + "\t");
System.out.println();
}*/
for(int i = 0; i < outputDatas.size(); i++)
for(int j = 0; j < outputDatas.get(0).size(); j++){
demo[i][0] = books[i][1];
if(j == 2)
demo[i][3] = counter.get(i) + "本可借";
else
demo[i][j + 1] = outputDatas.get(i).get(j);
}
String[] head = {"可借编号","书名","作者","借阅状态"};
DefaultTableModel tableModel = new DefaultTableModel(demo,head);
JTable table = new JTable(tableModel);
JScrollPane scroll = new JScrollPane(table);
panel.add(scroll);
panel.revalidate();
}
}
// for(int i = 0; i < outputDatas.size(); i++)
// System.out.println(outputDatas.get(i));}
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动");
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库");
e1.printStackTrace();
}
}
// 拿到要查询的信息并输出到主界面
public void numFindIndo(JPanel panel,JTextField text){
ArrayList array = new ArrayList();
Connection conn;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstorage","root","123456");
// if(!conn.isClosed())
// System.out.println("成功打开数据库");
String sql = "select * from books";
preparedStatement = conn.prepareStatement(sql);
ResultSet result = preparedStatement.executeQuery();
while(result.next()){
if(result.getString("id").equals(text.getText())){
array.add(result.getString("id"));
array.add(result.getString("title"));
array.add(result.getString("author"));
}
}
Object[][] demo = new Object[1][array.size()];
for(int i = 0; i < array.size(); i++)
demo[0][i] = array.get(i);
String[] head = {"编号","书名","作者"};
DefaultTableModel tableModel = new DefaultTableModel(demo,head);
JTable table = new JTable(tableModel);
JScrollPane scroll = new JScrollPane(table);
panel.add(scroll);
panel.revalidate();
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动");
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库");
e1.printStackTrace();
}
}
}
查询全部信息(查询文本框中无内容):
按关键字查询:
3、读者模块
读者模块包括四个操作,其一是用户注册与登录,其二是查询自身的借阅信息,其三是借阅图书,最后一个是归还图书。
用户注册与登录:用户若要借书,则需要先进行注册,然后登录。注册成功后则其注册信息会写入数据库以便以后登录使用。若登陆密码或账号错误,则会有相应提示信息。
查询自身的借阅信息:若用户已经注册并且登录成功,可以通过这一某块查看自己的借阅信息(一般是看是否借阅超期)。可以显示的内容有借阅的图书编号、图书名、借书时间、应还日期、距离应还日期的天数以及借阅状态(是否超期)。
借阅图书:在此模块可以根据想要借阅的图书编号借阅图书。
归还图书:在此模块可以根据想要归还的图书编号归还图书。
用户登录代码:package per.tushu.frame;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JComboBox;
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.SwingConstants;
public class UserLoginFrame extends JFrame{
JLabel label,name,pass,identify;
JButton login,register,modify;
JTextField adminName;
JPasswordField password;
JPanel panel,jp1,jp2;
JPanel[] panelLeft,panelRight;
JComboBox personType;
public UserLoginFrame(){
this.setBounds(400, 200, 300, 200);
this.setTitle("登录系统");
this.setLayout(new BorderLayout());
label = new JLabel("登录",SwingConstants.CENTER);
label.setFont(new Font("楷体",Font.BOLD,30));
name = new JLabel("账 号");
pass = new JLabel("密 码");
adminName = new JTextField(12);
adminName.setHorizontalAlignment(SwingConstants.CENTER);
password = new JPasswordField(12);
password.setHorizontalAlignment(SwingConstants.CENTER);
password.setEchoChar('*'); //设置回显字符
panel = new JPanel();
jp1 = new JPanel();
jp2 = new JPanel();
panel.setLayout(new BorderLayout());
jp1.add(adminName);
jp1.add(name);
jp1.add(password);
jp1.add(pass);
panel.add(jp1);
register = new JButton("注册");
login = new JButton("登录");
modify = new JButton("修改密码");
jp2.add(register);
jp2.add(login);
jp2.add(modify);
panel.add(jp2,BorderLayout.SOUTH);
this.add(label,BorderLayout.NORTH);
this.add(panel);
MyEvent();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void MyEvent(){
// 注册事件处理
register.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
new RegisterFrame().show();
}
});
// 登录事件处理
login.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Connection conn;
PreparedStatement preparedStatement;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstorage","root","123456");
// if(!conn.isClosed())
// System.out.println("成功打开数据库");
String sql = "select word from password where id='" + adminName.getText() + "'";
preparedStatement = conn.prepareStatement(sql);
ResultSet result = preparedStatement.executeQuery();
// if(result.next())
// System.out.println(result.getString("word"));
String str1 = password.getText();
if(result.next()){
String str2 = result.getString("word");
if(str1.equals(str2))
new UserInfoFrame(adminName).show();
else{
String info = "你输入的密码不正确,原因可能是:\n" + "1、忘记密码;\n" + "2、未开启小键盘;\n" + "3、大小写未区分。";
JOptionPane.showMessageDialog(null, info,"系统信息",JOptionPane.INFORMATION_MESSAGE);
// new LoginErrorFrame().show();
}
}else
JOptionPane.showMessageDialog(null, "用户不存在,请先注册!!!","系统信息",JOptionPane.WARNING_MESSAGE);
// new NoExist().show();
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动");
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库");
e1.printStackTrace();
}
UserLoginFrame.this.dispose();
}
});
// 修改密码
modify.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
}
//
public static void main(String[] args){
new UserLoginFrame();
}
}
代码执行后显示如下:
用户注册代码:package per.tushu.frame;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import per.tushu.storage.PutinStorage;
public class RegisterFrame extends JFrame{
JPanel panel;
JTextField text;
JPasswordField password1,password2;
JLabel title,user,pass1,pass2;
JButton button;
public RegisterFrame(){
this.setBounds(400,200,300,200);
this.setTitle("注册");
this.setLayout(new BorderLayout());
title = new JLabel("注册",SwingConstants.CENTER);
title.setFont(new Font("楷体",Font.BOLD,30));
panel = new JPanel();
text = new JTextField(15);
text.setHorizontalAlignment(SwingConstants.CENTER);
password1 = new JPasswordField(15);
password1.setEchoChar('*');
password1.setHorizontalAlignment(SwingConstants.CENTER);
password2 = new JPasswordField(15);
password2.setEchoChar('*');
password2.setHorizontalAlignment(SwingConstants.CENTER);
user = new JLabel("用 户");
pass1 = new JLabel("密 码");
pass2 = new JLabel("确认密码");
button = new JButton("注册成功");
panel.add(text);
panel.add(user);
panel.add(password1);
panel.add(pass1);
panel.add(password2);
panel.add(pass2);
this.add(title,BorderLayout.NORTH);
this.add(panel);
this.add(button,BorderLayout.SOUTH);
MyEvent();
// this.setVisible(true);
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void MyEvent(){
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String userPassword1 = password1.getText();
// System.out.println(userPassword1);
String userPassword2 = password2.getText();
if(userPassword1.equals(userPassword2)){
// TODO Auto-generated method stub
new PutinStorage().userInfo(userPassword1,userPassword2,text);
new UserLoginFrame().show();
}else
JOptionPane.showMessageDialog(null, "两次密码不一致,请重新输入密码!!!","系统信息",JOptionPane.WARNING_MESSAGE);
// new RegistError().show();
}
});
}
// public static void main(String[] args){
// new RegisterFrame();
// }
}
注册窗体:
若用户不存在:
其他功能均在UserInfoFrame类中实现,代码如下:package per.tushu.frame;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
public class UserInfoFrame extends JFrame{
JButton info,lend,returnBook;
JLabel label;
JPanel panel,panelButton,panelInfo,panelInfo1,panelInfo2,panelInfo3;
CardLayout card;
// 借书按钮面板信息所用变量
JButton ensure,find;
JTextField bookNum;
JPanel jp1,jp2,jp3;
JTextField textField;
DefaultTableModel tableModel;
JTable table ;
public UserInfoFrame(JTextField text){
textField = text;
card = new CardLayout();
this.setBounds(300,200,600,450);
this.setTitle("借阅信息");
label = new JLabel(text.getText() + "的借阅信息",SwingConstants.CENTER);
label.setFont(new Font("楷体",Font.BOLD,30));
panel = new JPanel();
panel.setLayout(new BorderLayout());
panelInfo = new JPanel();
panelButton = new JPanel();
panelInfo1 = new JPanel();
panelInfo1.setLayout(new BorderLayout());
panelInfo2 = new JPanel();
panelInfo2.setLayout(new BorderLayout());
panelInfo3 = new JPanel();
panelInfo3.setLayout(new BorderLayout());
panelInfo.setLayout(card);
panelButton.setLayout(new FlowLayout(FlowLayout.CENTER));
info = new JButton("借阅信息");
lend = new JButton("借书");
returnBook = new JButton("还书");
panelButton.add(info);
panelButton.add(lend);
panelButton.add(returnBook);
// panelInfo1.setBackground(Color.red);
// panelInfo2.setBackground(Color.blue);
panelInfo.add(panelInfo1,"panelInfo1");
panelInfo.add(panelInfo2,"panelInfo2");
panelInfo.add(panelInfo3,"panelInfo3");
panel.add(panelButton,BorderLayout.NORTH);
panel.add(panelInfo);
this.add(label,BorderLayout.NORTH);
this.add(panel);
MyEvent();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// 信息显示
class NumFindInfo{
public NumFindInfo(JPanel panel,JTextField text,String tableName){
ArrayList array = new ArrayList();
Connection conn;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstorage","root","123456");
// if(!conn.isClosed())
// System.out.println("成功打开数据库");
String sql = null;
if(tableName.equals("books"))
sql = "select * from " + tableName;
else
sql = "select * from " + tableName;
preparedStatement = conn.prepareStatement(sql);
ResultSet result = preparedStatement.executeQuery();
while(result.next()){
if(result.getString("id").equals(text.getText()) && tableName.equals("books")){
array.add(result.getString("id"));
array.add(result.getString("title"));
array.add(result.getString("author"));
}
// else if(result.getString("id").equals(text.getText()) && tableName.equals("lendInfo")){
// array.add(result.getString("id"));
// array.add(result.getString("title"));
// array.add(result.getString("time"));
// }
}
Object[][] demo = new Object[1][array.size()];
for(int i = 0; i < array.size(); i++)
demo[0][i] = array.get(i);
// for(int i = 0; i < array.size(); i++)
// System.out.println(array.get(i));
// if(tableName.equals("books"))
String[] head1 = {"编号","书名","作者"};
String[] head2 = {"编号","书名","借阅事件"};
if(tableName.equals("books"))
tableModel = new DefaultTableModel(demo,head1);
else
tableModel = new DefaultTableModel(demo,head2);
table = new JTable(tableModel);
JScrollPane scroll = new JScrollPane(table);
panel.add(scroll);
panel.revalidate();
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动");
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库");
e1.printStackTrace();
}
}
}
public void MyEvent(){
// 借书
lend.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
// 借书按钮所示卡片信息
ensure = new JButton("确认借阅");
find = new JButton("查找");
bookNum = new JTextField(10);
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jp1.add(bookNum);
jp1.add(find);
jp2.add(ensure);
panelInfo1.add(jp1,BorderLayout.NORTH);
panelInfo1.add(jp2,BorderLayout.SOUTH);
// 查找事件处理
find.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
new NumFindInfo(panelInfo1,bookNum,"books");
}
});
// 确定借阅事件处理
ensure.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
// 获取系统时间(按照格式“年-月-日”)
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// System.out.println(time);
Connection conn;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstorage","root","123456");
// if(!conn.isClosed())
// System.out.println("成功打开数据库");
String sql = "insert into lendInfo values ('" + textField.getText() + "','" + table.getValueAt(0, 0) + "','" + table.getValueAt(0, 1) + "','" + time + "')";
preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
String sql1 = "update books set state='借出' where id='" + bookNum.getText() + "'";
preparedStatement = conn.prepareStatement(sql1);
preparedStatement.executeUpdate();
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动");
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库");
e1.printStackTrace();
}
}
});
panelInfo1.validate();
card.show(panelInfo, "panelInfo1");
}
});
// 借阅信息
info.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
ArrayList> array = new ArrayList>();
Connection conn;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstorage","root","123456");
// if(!conn.isClosed())
// System.out.println("成功打开数据库");
String sql = "select * from lendInfo where lendName='" + textField.getText() + "'";
preparedStatement = conn.prepareStatement(sql);
ResultSet result = preparedStatement.executeQuery();
// if(!result.next())
// JOptionPane.showMessageDialog(null, "结果集中无记录");
// else{
while(result.next()){
ArrayList al = new ArrayList();
al.add(result.getString("id"));
al.add(result.getString("title"));
al.add(result.getString("time"));
array.add(al);
}
int row = array.size();
int column = array.get(0).size();
Object[][] demo = new Object[row][column + 3];
String[] times = new String[row];
String[] days = new String[row];
String[] overDays = new String[row];
// 计算应还日期(以30天为期限)
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for(int i = 0; i < row; i++){
String firstTime = array.get(i).get(2);
Date date = df.parse(firstTime);
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.add(Calendar.DAY_OF_YEAR,30);
times[i] = df.format(rightNow.getTime());
}
// 计算还需多少天到还书日期(以天为计算单位)
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
for(int i = 0; i < row; i++){
String firstTime = times[i];
Date date = df1.parse(firstTime);
long day = (date.getTime() - new Date().getTime())/(24*60*60*1000);
days[i] = String.valueOf(day);
if(day < 0)
overDays[i] = "超期" + (0 - day) + "天";
else if(day >= 0)
overDays[i] = "未超期";
}
for(int i = 0; i < row; i++)
for(int j = 0; j <= column + 2; j++){
if(j < column)
demo[i][j] = array.get(i).get(j);
else if(j == column)
demo[i][j] = times[i];
else if(j == column + 1)
demo[i][j] = days[i];
else
demo[i][j] = overDays[i];
}
String[] head = {"编号","书名","借书时间","应还日期","剩余天数","状态"};
DefaultTableModel tableModelInfo = new DefaultTableModel(demo,head);
JTable tableInfo = new JTable(tableModelInfo);
JScrollPane s = new JScrollPane(tableInfo);
panelInfo2.add(s);
panelInfo2.revalidate();
// }
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动");
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库");
e1.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
card.show(panelInfo, "panelInfo2");
}
});
// 还书
returnBook.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
// 借书按钮所示卡片信息
ensure = new JButton("确认还书");
// find = new JButton("查找");
bookNum = new JTextField(10);
jp1 = new JPanel();
jp1.add(bookNum);
jp1.add(ensure);
panelInfo3.add(jp1,BorderLayout.NORTH);
// 确定还书事件处理
ensure.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
// 获取系统时间(按照格式“年-月-日”)
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// System.out.println(time);
Connection conn;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstorage","root","123456");
// if(!conn.isClosed())
// System.out.println("成功打开数据库");
String sql = "delete from lendInfo where id='" + bookNum.getText() + "'";
preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动");
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库");
e1.printStackTrace();
}
}
});
panelInfo3.revalidate();
card.show(panelInfo, "panelInfo3");
}
});
}
// public static void main(String[] args){
// JTextField text = new JTextField("张三");
// new UserInfoFrame(text);
// }
}
查阅自身借阅信息:
借书(按图书编号借书):
还书(按图书编号还书):
4、以上各功能所用到的数据库处理,除了上述提到的FindBook类后,还有一个是PutinStorage,代码如下:package per.tushu.storage;
import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
public class PutinStorage {
// 将用户名和密码存放在password表中
public void userInfo(String userPassword1,String userPassword2,JTextField text){
Connection conn;
PreparedStatement preparedStatement;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstorage","root","123456");
// if(!conn.isClosed())
// System.out.println("成功打开数据库");
String userName = text.getText();
// System.out.println(userName);
// 按账号查找
// String sql2 = "select * from password where id='" + userName + "'";
// preparedStatement = conn.prepareStatement(sql2);
// ResultSet result = preparedStatement.executeQuery();
// if(!result.wasNull()){
//// new DataRepeat().show();
// System.out.println(result.getString("id") + "\t" + result.getString("password"));
// }
String sql = "insert into password values('" + userName + "','" + userPassword1 + "')";
preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动");
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库");
e1.printStackTrace();
}
}
// 将可视化界面中表的数据储存到数据库
public void saveData(JTable table){
int column = table.getColumnCount();
int row = table.getRowCount();
// System.out.println("rows:" + row + " coumns:" +column);
String[][] value = new String[row][column];
/*String[] name = new String[column];
String[][] value = new String[row][column];
for(int i = 0; i < column; i++){
name[i] = table.getColumnName(i);
}*/
/*for(int i = 0; i < column; i++){
System.out.println(name[i]);
}*/
// System.out.println(table.getColumnCount());
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
// System.out.println(table.getValueAt(i, j).toString());
value[i][j] = table.getValueAt(i, j).toString();
// System.out.println(value[i][j]);
}
}
// for(int i = 0; i < row; i++){
// for(int j = 0; j < column; j++)
// System.out.println(value[i][j]);
// }
// TODO Auto-generated method stub
String sql_url = "jdbc:mysql://localhost:3306/bookstorage"; //数据库路径(一般都是这样写),test是数据库名称
String name = "root"; //用户名
String password = "123456"; //密码
Connection conn;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //连接驱动
conn = DriverManager.getConnection(sql_url, name, password); //连接数据库
// if(!conn.isClosed())
// System.out.println("成功连接数据库");
preparedStatement = conn.prepareStatement("delete from books where true");
preparedStatement.executeUpdate();
for(int i = 0; i < row; i++){
// System.out.println("==========================");
String sql = "insert into books values('" + value[i][0] + "','" + value[i][1] + "','"+ value[i][2] + "','"+ value[i][3] + "','"+ value[i][4] + "','"+ value[i][5] + "','"+ value[i][6] + "','"+ value[i][7] + "')";
// System.out.println(sql);
preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
}
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动。");
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库。");
e1.printStackTrace();
}
}
// 得到数据库表数据
public static Vector getRows(String tableName){
String sql_url = "jdbc:mysql://localhost:3306/bookstorage"; //数据库路径(一般都是这样写),test是数据库名称
String name = "root"; //用户名
String password = "123456"; //密码
Connection conn;
PreparedStatement preparedStatement = null;
Vector rows = null;
Vector columnHeads = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //连接驱动
conn = DriverManager.getConnection(sql_url, name, password); //连接数据库
// if(!conn.isClosed())
// System.out.println("成功连接数据库");
preparedStatement = conn.prepareStatement("select * from " + tableName);
ResultSet result1 = preparedStatement.executeQuery();
// boolean moreRecords = result1.next();
// if(result1.wasNull())
// JOptionPane.showMessageDialog(null, "结果集中无记录");
rows = new Vector();
// while(result1.next())
// System.out.println(result1.getInt("id")+"\t"+result1.getString("name"));
ResultSetMetaData rsmd = result1.getMetaData();
while(result1.next()){
rows.addElement(getNextRow(result1,rsmd));
}
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动。");
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库。");
e.printStackTrace();
}
return rows;
}
// 得到数据库表头
public static Vector getHead(String tableName){
String sql_url = "jdbc:mysql://localhost:3306/bookstorage"; //数据库路径(一般都是这样写),test是数据库名称
String name = "root"; //用户名
String password = "123456"; //密码
Connection conn;
PreparedStatement preparedStatement = null;
Vector columnHeads = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //连接驱动
conn = DriverManager.getConnection(sql_url, name, password); //连接数据库
// if(!conn.isClosed())
// System.out.println("成功连接数据库");
preparedStatement = conn.prepareStatement("select * from " + tableName);
// preparedStatement = conn.prepareStatement("select * from 计算机");
ResultSet result1 = preparedStatement.executeQuery();
boolean moreRecords = result1.next();
if(!moreRecords)
JOptionPane.showMessageDialog(null, "结果集中无记录");
columnHeads = new Vector();
ResultSetMetaData rsmd = result1.getMetaData();
for(int i = 1; i <= rsmd.getColumnCount(); i++)
columnHeads.addElement(rsmd.getColumnName(i));
preparedStatement.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动。");
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库。");
e.printStackTrace();
}
return columnHeads;
}
// 得到数据库中下一行数据
private static Vector getNextRow(ResultSet rs,ResultSetMetaData rsmd) throws SQLException{
Vector currentRow = new Vector();
for(int i = 1; i <= rsmd.getColumnCount(); i++){
currentRow.addElement(rs.getString(i));
}
return currentRow;
}
/*//使用PreparedStatement对mysql数据库进行创建表,增加数据,查询数据和删除数据过程
public static void process1(){
System.out.println("process1");
String sql_url = "jdbc:mysql://localhost:3306/test"; //数据库路径(一般都是这样写),test是数据库名称
String name = "root"; //用户名
String password = "123456"; //密码
Connection conn;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //连接驱动
conn = DriverManager.getConnection(sql_url, name, password); //连接数据库
if(!conn.isClosed())
System.out.println("成功连接数据库");
//新建表
String sql = "create table aa(id int,name text)";
preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
//在表中添加内容
// preparedStatement.executeUpdate("insert into aa values(4,'amy')");
preparedStatement = conn.prepareStatement("insert into aa values(1,'张三')");
preparedStatement.executeUpdate();
preparedStatement = conn.prepareStatement("insert into aa values(2,'李四')");
preparedStatement.executeUpdate();
preparedStatement = conn.prepareStatement("insert into aa values(3,'王五')");
preparedStatement.executeUpdate();
//查询表内容
System.out.println("第一次查询表内容(删除前)");
preparedStatement = conn.prepareStatement("select * from aa");
ResultSet result1 = preparedStatement.executeQuery();
while(result1.next())
System.out.println(result1.getInt("id")+"\t"+result1.getString("name"));
//删除表中数据
preparedStatement = conn.prepareStatement("delete from aa where id = 2");
preparedStatement.executeUpdate();
//查询表中内容
System.out.println("第二次查询表内容(删除后)");
preparedStatement = conn.prepareStatement("select * from aa");
ResultSet result2 = preparedStatement.executeQuery();
while(result2.next())
System.out.println(result2.getInt("id")+"\t"+result2.getString("name"));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动。");
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库。");
e.printStackTrace();
}
}
//使用Statement对mysql数据库进行创建表,增加数据,查询数据和删除数据过程
public static void process2(){
System.out.println("process2");
String sql_url = "jdbc:mysql://localhost:3306/test"; //数据库路径(一般都是这样写),test是数据库名称
String name = "root"; //用户名
String password = "123456"; //密码
Connection conn;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //连接驱动
conn = DriverManager.getConnection(sql_url, name, password); //连接数据库
if(!conn.isClosed())
System.out.println("成功连接数据库");
statement = conn.createStatement();
//新建表
String sql = "create table bb(id int,name text)";
statement.executeUpdate(sql);
//在表中添加内容
statement.executeUpdate("insert into bb values(1,'张三')");
statement.executeUpdate("insert into bb values(2,'李四')");
statement.executeUpdate("insert into bb values(3,'王五')");
//查询表内容
System.out.println("第一次查询表内容(删除前)");
ResultSet result1 = statement.executeQuery("select * from bb");
while(result1.next())
System.out.println(result1.getInt("id")+"\t"+result1.getString("name"));
//删除表中数据
statement.executeUpdate("delete from bb where id = 2");
//查询表内容
System.out.println("第二次查询表内容(删除后)");
ResultSet result2 = statement.executeQuery("select * from bb");
while(result2.next())
System.out.println(result2.getInt("id")+"\t"+result2.getString("name"));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("未成功加载驱动。");
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("未成功打开数据库。");
e.printStackTrace();
}
}
public static void main(String[] args){
process1();
// process2();
}*/
/*//主函数
public static void main(String[] args){
// table("computer");
// Find();
getRows();
}*/
}
这个系统没有用到windbuilder等可视化工具,也没有进行页面美化的操作,因此执行结果相对来说不太好看,仅是实现了基本功能,而且其中的极个别按键没有赋予功能,还需改善。完整工程我会上传到博客中的资源区,需要的可以下载。