用java的swing元件實現簡易的圖書管理系統
圖書管理系統在生活和學校中是最為常見的,這學期的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<String> yearArray = new ArrayList<String>();
// 獲取系統時間
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<ArrayList<String>> valueDay = new ArrayList<ArrayList<String>>();
ArrayList<String> value;
for(int i = 0; i < 12; i++){
if(i == 1){
value = new ArrayList<String>();
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<String>();
for(int j = 0; j < 31; j++)
value.add(String.valueOf(j + 1));
}
else{
value = new ArrayList<String>();
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<ArrayList<String>> datas = new ArrayList<ArrayList<String>>(); // 資料庫中所有的圖書資訊
ArrayList<ArrayList<String>> outputDatas = new ArrayList<ArrayList<String>>(); // 記錄需要輸出的資訊(中間量)
ArrayList<ArrayList<String>> bookN = new ArrayList<ArrayList<String>>(); // 所有可借書籍的資訊(在記錄可借書的ID號時用到,屬中間量)
ArrayList<ArrayList<String>> outputBook = new ArrayList<ArrayList<String>>(); //記錄所有可借書籍的ID號
ArrayList<String> lendBooks = new ArrayList<String>(); //儲存所有書籍的名稱
// 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<String> al = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
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<String> mid = new ArrayList<String>();
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<String> mid = new ArrayList<String>();
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<String> array = new ArrayList<String>();
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();
// }
}
註冊窗體:
若使用者不存在:
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<String> array = new ArrayList<String>();
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<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
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<String> al = new ArrayList<String>();
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);
// }
}
查閱自身借閱資訊:
借書(按圖書編號借書):
還書(按圖書編號還書):
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) {