項目用的是三層結構:分别是界面層,業務邏輯層,持久層。
我主要負責的是Book業務實體的三層代碼編寫。
1.持久層用了一個通用接口BaseDao以裝各個業務實體在持久層的共同方法。
package com.lovo.dao;
import java.util.List;
import com.lovo.bean.PageBean;
public interface BaseDao<E,K> {
/**
* 基礎 方法1:按照對象删除
* 持久層
* 輸入一個對象 删除該對象
* @param entity
*/
public boolean delete(E entity);
/**
* 基礎 方法2:按照ID删除
* 持久層
* 輸入對象ID 删除該ID的對象
* @param id
*/
public boolean deleteByKey(K id);
/**
* 基礎 方法3:查找全部
* 持久層
* 查找全部 對象類型的資料
* @return 裝有該類對象的容器
*/
public List<E> findAll();
/**
* 基礎 方法4:按照ID查找
* 持久層
* 按照ID 查找對象
* @param id
*/
public E findByKey(K id);
/**
* 基礎 方法5:給一個對象 儲存(建立)該對象
* 持久層
* 輸入一個對象 儲存該對象
* @param entity
*/
public boolean save(E entity);
/**
* 基礎 方法6:給一個對象 修改該對象
* 持久層
* 輸入一個對象 将資料庫内 該對象的屬性 修改為 輸入的對象的屬性
* @param entity
*/
public boolean update(E entity);
/**
* 基礎 方法7:分頁查找
* !!!!!!!新加的!!!!!!!
* 持久層
* 按照每頁顯示數量size 和 第幾頁page 查找書籍
*/
public PageBean<E> findByPage(int page, int size, Object... pramas);
/**
* 基礎 方法8:多條件查找
* !!!!!!!新加的!!!!!!!
* 持久層
* 按照給定條件查找
*/
public List<E> findByWays(Object...params);
}
2.相應的,在dao層實作包裡有一個抽象類做BaseDao的擴充卡
package com.lovo.dao.impl;
import java.util.List;
import com.lovo.bean.PageBean;
import com.lovo.dao.BaseDao;
public class BaseDaoAdapter<E, K> implements BaseDao<E,K> {
/**
* 構造器
*/
public BaseDaoAdapter(){
}
/**
* 基礎 方法1:按照對象删除
* 持久層 擴充卡
* 輸入一個對象 删除該對象
* @param entity
*/
public boolean delete(E entity){
return false;
}
/**
* 基礎 方法2:按照ID删除
* 持久層 擴充卡
* 輸入對象ID 删除該ID的對象
* @param id
*/
public boolean deleteByKey(K id){
return false;
}
/**
* 基礎 方法3:查找全部
* 持久層 擴充卡
* 查找全部 對象類型的資料
* @return 裝有該類對象的容器
*/
public List<E> findAll(){
return null;
}
/**
* 基礎 方法4:按照ID查找
* 持久層
* 按照ID 查找對象
* @param id
*/
public E findByKey(K id){
return null;
}
/**
* 基礎 方法5:給一個對象 儲存(建立)該對象
* 持久層
* 輸入一個對象 儲存該對象
* @param entity
*/
public boolean save(E entity){
return false;
}
/**
* 基礎 方法6:給一個對象 修改該對象
* 持久層
* 輸入一個對象 将資料庫内 該對象的屬性 修改為 輸入的對象的屬性
* @param entity
*/
public boolean update(E entity){
return false;
}
/**
* 基礎 方法7:分頁查找
* !!!!!!!新加的!!!!!!!
* 持久層
* 按照每頁顯示數量size 和 第幾頁page 查找書籍
*/
@Override
public PageBean<E> findByPage(int page, int size,Object... pramas) {
return null;
}
/**
* 基礎 方法8:多條件查找
* !!!!!!!新加的!!!!!!!
* 持久層
* 按照給定條件查找
*/
public List<E> findByWays(Object...params){
return null;
}
}
3.book業務實體的dao層實作代碼
package com.lovo.dao.impl;
import java.util.List;
import com.lovo.bean.PageBean;
import com.lovo.dao.BaseDao;
public class BaseDaoAdapter<E, K> implements BaseDao<E,K> {
/**
* 構造器
*/
public BaseDaoAdapter(){
}
/**
* 基礎 方法1:按照對象删除
* 持久層 擴充卡
* 輸入一個對象 删除該對象
* @param entity
*/
public boolean delete(E entity){
return false;
}
/**
* 基礎 方法2:按照ID删除
* 持久層 擴充卡
* 輸入對象ID 删除該ID的對象
* @param id
*/
public boolean deleteByKey(K id){
return false;
}
/**
* 基礎 方法3:查找全部
* 持久層 擴充卡
* 查找全部 對象類型的資料
* @return 裝有該類對象的容器
*/
public List<E> findAll(){
return null;
}
/**
* 基礎 方法4:按照ID查找
* 持久層
* 按照ID 查找對象
* @param id
*/
public E findByKey(K id){
return null;
}
/**
* 基礎 方法5:給一個對象 儲存(建立)該對象
* 持久層
* 輸入一個對象 儲存該對象
* @param entity
*/
public boolean save(E entity){
return false;
}
/**
* 基礎 方法6:給一個對象 修改該對象
* 持久層
* 輸入一個對象 将資料庫内 該對象的屬性 修改為 輸入的對象的屬性
* @param entity
*/
public boolean update(E entity){
return false;
}
/**
* 基礎 方法7:分頁查找
* !!!!!!!新加的!!!!!!!
* 持久層
* 按照每頁顯示數量size 和 第幾頁page 查找書籍
*/
@Override
public PageBean<E> findByPage(int page, int size,Object... pramas) {
return null;
}
/**
* 基礎 方法8:多條件查找
* !!!!!!!新加的!!!!!!!
* 持久層
* 按照給定條件查找
*/
public List<E> findByWays(Object...params){
return null;
}
}
4.book業務實體業務邏輯層的代碼,大部分是過渡代碼。
package com.lovo.biz.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.lovo.bean.PageBean;
import com.lovo.biz.BooksService;
import com.lovo.dao.BooksDao;
import com.lovo.dao.ReaderDao;
import com.lovo.dao.impl.BooksDaoDbImpl;
import com.lovo.dao.impl.ReaderDaoImpl;
import com.lovo.entity.BookType;
import com.lovo.entity.Books;
import com.lovo.entity.BorrowList;
import com.lovo.entity.Reader;
import com.lovo.util.DbSessionFactory;
public class BooksServiceImpl extends BaseServiceAdaper<Books, Integer>
implements BooksService<Books, Integer> {
private BooksDao<Books, Integer> booksDao = new BooksDaoDbImpl();
private ReaderDao<Reader, Integer> readerDao = new ReaderDaoImpl();
/**
* 預設無參構造器
*/
public BooksServiceImpl() {
}
/**
* 重寫 Books專有 方法1: 借書
* @c 邏輯業務層 輸入讀者和書的ID 生成 借書單的對象
* @param readerID
* @param bookID
* @return 成功傳回true
*/
@Override
public BorrowList borrow(int readerID, int bookID) {
BorrowList blist = new BorrowList();
try {
DbSessionFactory.openSession();
Books book = booksDao.findByKey(bookID);
book.borrowOut();
booksDao.updateNumber(book);
Reader reader = readerDao.findByKey(readerID);
reader.borrowOut();
readerDao.updateCurrentNumber(reader);
blist.setBorrowID((int) (System.currentTimeMillis()-100000));
blist.setBook(book);
blist.setReader(reader);
blist.setOperatorID(6001);
blist.setBorrowDate(System.currentTimeMillis());
blist.setIsBack("未");
booksDao.saveBorrowList(blist);
} finally {
DbSessionFactory.closeSession();
}
return blist;
}
/**
* 重寫 Books專有 方法2:還書
* @c 邏輯業務層
* @c 輸入讀者和書的ID 查找并完成借書單據
* @param readerID
* @param bookID
*/
@Override
public BorrowList bookBack(int readerID, int bookID) {
BorrowList blist = new BorrowList();
try {
DbSessionFactory.openSession();
blist=booksDao.findByTwoKey(readerID,bookID);
blist.setBackDate(System.currentTimeMillis());
blist.setBackManagerID(6002);
blist.setIsBack("已");
booksDao.updateBorrowList(blist);
Books book = booksDao.findByKey(bookID);
book.bookBack();
booksDao.updateNumber(book);
Reader reader = readerDao.findByKey(readerID);
reader.bookBack();
readerDao.updateCurrentNumber(reader);
} finally {
DbSessionFactory.closeSession();
}
return blist;
}
/**
* 重寫 Books專業 方法3:查找書籍的詳細資訊
* @c 邏輯業務層
* @c 輸入bookID 傳回書籍詳細資訊的對象
*/
@Override
public Books findAllInfo(int bookID) {
// TODO Auto-generated method stub
return null;
}
/**
* 重寫 Books專有 方法4:按照多屬性查詢書籍
* @c 邏輯業務層
* @param 代替多個對象
* @param params
*/
@Override
public List<Books> findByWays(Object... params) {
List<Books> list = null;
try {
DbSessionFactory.openSession();
list = booksDao.findByWays(params);
} finally {
DbSessionFactory.closeSession();
}
return list;
}
/**
* 重寫 Books專有方法5:查詢所有基本書本類型
* @return
*/
@SuppressWarnings("rawtypes")
@Override
public List<List> findAllBookType() {
try {
DbSessionFactory.openSession();
return booksDao.findAllBookType();
} finally {
DbSessionFactory.closeSession();
}
}
/**
* 重寫 Books專有方法6:查詢所有次級書本類型
* @return
*/
@Override
public List<BookType> findAllBaseType() {
try {
DbSessionFactory.openSession();
return booksDao.findAllBaseType();
} finally {
DbSessionFactory.closeSession();
}
}
/**
* 重寫 基礎 方法7:分頁查找
* @c!!!!!!!新加的!!!!!!!
* @c邏輯業務層 按照每頁顯示數量size 和 第幾頁page 查找書籍
*/
@Override
public PageBean<Books> findByPage(int page,int size, Object... pramas) {
DbSessionFactory.openSession();
// 查詢所有書本
PageBean<Books> bean = booksDao.findByPage(page,size,pramas);
DbSessionFactory.closeSession();
return bean;
}
/**
* 重寫 基礎 方法2:按照ID删除
* 業務邏輯層 總接口
* 輸入對象ID 删除該ID的對象
* @param id
*/
@Override
public boolean deleteByKey(Integer id) {
try {
DbSessionFactory.openSession();
return booksDao.deleteByKey(id);
} finally {
DbSessionFactory.closeSession();
}
}
/**
* 重寫 基礎 方法5:給一個對象 儲存(建立)該對象
* 業務邏輯層 總接口
* 輸入一個對象 儲存該對象
* @param entity
*/
@Override
public boolean save(Books entity) {
try {
DbSessionFactory.openSession();
return booksDao.save(entity);
} finally {
DbSessionFactory.closeSession();
}
}
/**
* 重寫 基礎 方法6:給一個對象 修改該對象
* 業務邏輯層 總接口
* 輸入一個對象 将資料庫内 該對象的屬性 修改為 輸入的對象的屬性
* @param entity
*/
@Override
public boolean update(Books entity){
try {
DbSessionFactory.openSession();
return booksDao.update(entity);
} finally {
DbSessionFactory.closeSession();
}
}
@Override
public PageBean<BorrowList> findBorrowList(int page, int size, int readerid) {
PageBean<BorrowList> pageBean=null;
try {
DbSessionFactory.openSession();
pageBean= booksDao.findBorrowList(page,size,readerid);
Map<Integer, Books> booksMap = new HashMap<Integer, Books>();
List<Books> booksList = booksDao.findAll();
for (Books temp : booksList) {
booksMap.put(temp.getBookID(), temp);
}
List<BorrowList> borrowList = pageBean.getList();
for (BorrowList temp : borrowList) {
temp.setBook(booksMap.get(temp.getBook().getBookID()));
}
Map<Integer, Reader> map = new HashMap<Integer, Reader>();
List<Reader> readerList = readerDao.findAll();
for (Reader temp : readerList) {
map.put(temp.getReaderID(), temp);
}
List<BorrowList> borrowList1 = pageBean.getList();
for (BorrowList temp : borrowList1) {
temp.setReader(map.get(temp.getReader().getReaderID()));
}
} finally {
DbSessionFactory.closeSession();
}
return pageBean;
}
@Override
public Books findByKey(Integer id) {
try {
DbSessionFactory.openSession();
return booksDao.findByKey(id);
} finally {
DbSessionFactory.closeSession();
}
}
@Override
public PageBean<BorrowList> findBorrowListByBook(int page, int size,
int readerid, int bookid) {
PageBean<BorrowList> pageBean=null;
try {
DbSessionFactory.openSession();
pageBean= booksDao.findBorrowListByBook(page,size,readerid,bookid);
Map<Integer, Books> booksMap = new HashMap<Integer, Books>();
List<Books> booksList = booksDao.findAll();
for (Books temp : booksList) {
booksMap.put(temp.getBookID(), temp);
}
List<BorrowList> borrowList = pageBean.getList();
for (BorrowList temp : borrowList) {
temp.setBook(booksMap.get(temp.getBook().getBookID()));
}
Map<Integer, Reader> map = new HashMap<Integer, Reader>();
List<Reader> readerList = readerDao.findAll();
for (Reader temp : readerList) {
map.put(temp.getReaderID(), temp);
}
List<BorrowList> borrowList1 = pageBean.getList();
for (BorrowList temp : borrowList1) {
temp.setReader(map.get(temp.getReader().getReaderID()));
}
} finally {
DbSessionFactory.closeSession();
}
return pageBean;
}
public BorrowList findTwoKey(int readerID,int bookID) {
try {
DbSessionFactory.openSession();
return booksDao.findByTwoKey(readerID, bookID);
} finally {
DbSessionFactory.closeSession();
}
}
}
5.新增,修改書籍界面代碼
package com.lovo.ui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileFilter;
import com.lovo.biz.impl.BooksServiceImpl;
import com.lovo.entity.BookType;
import com.lovo.entity.Books;
@SuppressWarnings("serial")
public class BookSaveJDialog extends JDialog implements ActionListener{
private JLabel[] labs = new JLabel[11];
private JLabel photoLabel;
private JTextField[] txts = new JTextField[10];
private JTextArea bookTxt;
private JComboBox<BookType> supperComboBox,typeComboBox;
private JButton okBtn,cancleBtn,imageBtn;
private JFileChooser imageChooser = new JFileChooser();
private Map<String, Integer> typeMap = new HashMap<String, Integer>();
@SuppressWarnings("unused")
private Map<String,Integer> baseMap = new HashMap<String, Integer>();
private String[] strs = {"書籍編号:","書籍ISBN:", "書籍名稱:", "作者:", "譯者:", "出版社:", "出版日期:",
"庫存數量:","價格:", "日租金:", "書籍類型:" };
private Books book;
private Image photo;
private JDialog fatherJDialog;
public BookSaveJDialog(Books tempBook,JDialog fatherJDialog) {
this.setModal(true);
this.fatherJDialog = fatherJDialog;
this.book = tempBook;
this.setTitle("新增書籍");
this.setSize(650, 750);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setLayout(null);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
loadData();
if(book != null) {
BookSaveJDialog.this.setTitle("修改書籍");
txts[0].setText(String.valueOf(book.getBookID()));
txts[1].setText(book.getBookISBN());
txts[2].setText(book.getBookName());
txts[3].setText(book.getAuthor());
txts[4].setText(book.getTranslator());
txts[5].setText(book.getPress());
txts[6].setText(String.valueOf(book.getPublicationDate()));
txts[7].setText(String.valueOf(book.getBookNumber()));
txts[8].setText(String.valueOf(book.getPrice()));
txts[9].setText(String.valueOf(book.getRentPerDay()));
bookTxt.setText(book.getFullInfo());
supperComboBox.setSelectedIndex(0);
typeComboBox.setSelectedIndex(0);
okBtn.setText("确認修改");
}
}
});
initComponents();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void loadData() {
//級聯下拉清單
List<BookType> baseTypeList = new BooksServiceImpl().findAllBaseType();
Vector<BookType> baseTypeVector = new Vector<BookType>(baseTypeList);
ComboBoxModel baseTypeModel = new DefaultComboBoxModel(baseTypeVector);
supperComboBox.setModel(baseTypeModel);
final List<List> fatherList = new BooksServiceImpl().findAllBookType();
Vector<BookType> bookTypeVector = new Vector<BookType>(fatherList.get(0));
ComboBoxModel bookTypeModel = new DefaultComboBoxModel(bookTypeVector);
typeComboBox.setModel(bookTypeModel);
for(int i = 0; i < fatherList.get(0).size(); i++) {
typeMap.put(( (BookType) fatherList.get(0).get(i)).getTypeName(), i);
}
//添加菜單選項改變監聽器事件
supperComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int index = supperComboBox.getSelectedIndex();
typeComboBox.removeAllItems();
Vector<BookType> bookTypeVector = new Vector<BookType>(fatherList.get(index));
ComboBoxModel bookTypeModel = new DefaultComboBoxModel(bookTypeVector);
typeComboBox.setModel(bookTypeModel);
for(int j = 0 ; j < fatherList.get(index).size();j++){
typeMap.put(((BookType) fatherList.get(index).get(j)).getTypeName(), j);
}
}
});
}
private void initComponents() {
for (int i = 0; i < labs.length; i++) {
labs[i] = new JLabel(strs[i],JLabel.RIGHT);
labs[i].setBounds(10, 30 + 60 * i, 100, 30);
this.add(labs[i]);
}
photoLabel = new JLabel("", JLabel.CENTER);
photoLabel.setBounds(380, 30, 200, 240);
photoLabel.setBorder(new LineBorder(Color.BLACK));
this.add(photoLabel);
for (int i = 0; i < txts.length; i++) {
txts[i] = new JTextField();
txts[i].setBounds(130, 30 + 60 * i, 200,30);
this.add(txts[i]);
}
bookTxt = new JTextArea("請輸入書籍的詳細資訊:");
bookTxt.setBounds(380, 340, 210,240);
bookTxt.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
if(bookTxt.getText().equals("請輸入書籍的詳細資訊:")){
bookTxt.setText("");
}
}
});
this.add(bookTxt);
supperComboBox = new JComboBox<BookType>();
supperComboBox.setBounds(130, 630, 100,30);
this.add(supperComboBox);
typeComboBox = new JComboBox<BookType>();
typeComboBox.setBounds(230, 630, 100,30);
this.add(typeComboBox);
okBtn = new JButton("确認新增");
okBtn.setBounds(180, 680, 100, 30);
this.add(okBtn);
cancleBtn = new JButton("取消");
cancleBtn.setBounds(370, 680, 100, 30);
this.add(cancleBtn);
imageBtn = new JButton("添加圖檔");
imageBtn.setBounds(420, 280, 100, 30);
this.add(imageBtn);
Font f = new Font("微軟雅黑", Font.PLAIN, 14);
for(Component c : this.getContentPane().getComponents()) {
c.setFont(f);
if(c instanceof JButton) {
((JButton) c).addActionListener(this);
}
}
imageChooser.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "圖檔檔案";
}
@Override
public boolean accept(File f) {
if(f.isFile()) {
String filename = f.getName();
int dotIndex = filename.lastIndexOf(".");
if(dotIndex > 0 && dotIndex < filename.length() - 1) {
String ext = filename.substring(dotIndex + 1);
return ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("png")
|| ext.equalsIgnoreCase("bmp") || ext.equalsIgnoreCase("gif");
}
}
return f.isDirectory();
}
});
}
// public static void main(String[] args) {
// new SaveFrame(book).setVisible(true);
//}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("确認新增")){
doAddBook();
}
else if(command.equals("确認修改")) {
doUpdatBook();
}
else if(command.equals("取消")) {
this.dispose();
fatherJDialog.setVisible(true);
}
else if(command.equals("添加圖檔")) {
if(imageChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
repaint();
}
}
}
//修改書籍
private void doUpdatBook() {
int bookId =Integer.parseInt(txts[0].getText());
String bookISBN=txts[1].getText().trim();
String bookName=txts[2].getText().trim();
String author=txts[3].getText().trim();
String translator=txts[4].getText().trim();
String press =txts[5].getText().trim();
long publicationDate=Long.parseLong(txts[6].getText().trim());
int number = Integer.parseInt(txts[7].getText().trim());
double price = Double.parseDouble(txts[8].getText().trim());
double rentpayday = Double.parseDouble(txts[9].getText().trim());
String fullInfo =bookTxt.getText();
BookType baseType=(BookType) supperComboBox.getItemAt(supperComboBox.getSelectedIndex());
BookType bookType=(BookType) typeComboBox.getItemAt(typeComboBox.getSelectedIndex());
book.setBookID(bookId);
book.setBookISBN(bookISBN);
book.setBookName(bookName);
book.setAuthor(author);
book.setTranslator(translator);
book.setPress(press);
book.setPublicationDate(publicationDate);
book.setBookNumber(number);
book.setPrice(price);
book.setRentPerDay(rentpayday);
book.setFullInfo(fullInfo);
book.setBaseType(baseType);
book.setBookType(bookType);
File f = imageChooser.getSelectedFile();
if(f != null) {
InputStream in = null;
byte[] buffer = new byte[(int) f.length()];
try {
in = new FileInputStream(f);
in.read(buffer);
book.setPicture(buffer);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if(in != null) {
try {
in.close();
}
catch (IOException e) {
}
}
}
}
if(new BooksServiceImpl().update(book)) {
JOptionPane.showMessageDialog(null, "修改成功");
this.dispose();
fatherJDialog.setVisible(true);
}
else {
JOptionPane.showMessageDialog(null, "修改失敗", "錯誤", JOptionPane.ERROR_MESSAGE);
}
}
//新增書籍
private void doAddBook() {
int bookId = Integer.parseInt(txts[0].getText().trim());
String bookISBN = txts[1].getText().trim();
String bookName = txts[2].getText().trim();
String author = txts[3].getText().trim();
String translator = txts[4].getText().trim();
String press = txts[5].getText().trim();
long publicationDate = Long.parseLong(txts[6].getText().trim());
int number = Integer.parseInt(txts[7].getText().trim());
double price = Double.parseDouble(txts[8].getText().trim());
double rentpayday = Double.parseDouble(txts[9].getText().trim());
String fullInfo = bookTxt.getText();
BookType baseType=(BookType) supperComboBox.getItemAt(supperComboBox.getSelectedIndex());
BookType bookType=(BookType) typeComboBox.getItemAt(typeComboBox.getSelectedIndex());
Books book1 = new Books();
book1.setBookID(bookId);
book1.setBookISBN(bookISBN);
book1.setBookName(bookName);
book1.setAuthor(author);
book1.setTranslator(translator);
book1.setPress(press);
book1.setPublicationDate(publicationDate);
book1.setBookNumber(number);
book1.setPrice(price);
book1.setRentPerDay(rentpayday);
book1.setFullInfo(fullInfo);
book1.setBaseType(baseType);
book1.setBookType(bookType);
File f = imageChooser.getSelectedFile();
if(f != null) {
InputStream in = null;
byte[] buffer = new byte[(int) f.length()];
try {
in = new FileInputStream(f);
in.read(buffer);
book.setPicture(buffer);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if(in != null) {
try {
in.close();
}
catch (IOException e) {
}
}
}
}
if(new BooksServiceImpl().save(book1)){
JOptionPane.showMessageDialog(null, "添加成功");
this.dispose();
// this.setVisible(false);
fatherJDialog.setVisible(true);
}
else {
JOptionPane.showMessageDialog(null, "添加失敗", "錯誤", JOptionPane.ERROR_MESSAGE);
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
File f = imageChooser.getSelectedFile();
if(photo != null) {
g.drawImage(photo, 380, 30, 200, 240, null);
}
if(f != null) {
Image image = Toolkit.getDefaultToolkit().getImage(f.getAbsolutePath());
g.drawImage(image, 380, 30, 200, 240, null);
}
}
}
6.借書界面
package com.lovo.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import com.lovo.bean.PageBean;
import com.lovo.biz.impl.BooksServiceImpl;
import com.lovo.biz.impl.ReaderServiceImpl;
import com.lovo.entity.Books;
import com.lovo.entity.BorrowList;
import com.lovo.entity.Reader;
import com.lovo.util.MyUtil;
/**
* 查詢資料視窗模型
*
* @author Administrator
*
*/
@SuppressWarnings("serial")
public class BorrowDialog extends JDialog implements ActionListener {
final Font NORMAL_FONT = new Font("微軟雅黑", Font.PLAIN, 16);
final Font BIG_FONT = new Font("微軟雅黑", Font.PLAIN, 70);
private JTable dataTable;
private JScrollPane dataPane;
private int page = 1;
private int size = 20;
private int totalPage = 1;
private BooksServiceImpl bookService = new BooksServiceImpl();
private ReaderServiceImpl readerService = new ReaderServiceImpl();
private JLabel[] labs = new JLabel[7];
private JTextField[] txts = new JTextField[7];
private JButton[] chooseButtons = new JButton[4];
private JButton readerBtn,bookBtn,okBtn,cancleBtn;
private JLabel hintLabel;
private String[] labelStrs={"讀者編号:","讀者姓名:","借書數量:","書籍編号:",
"書名:","數量:","日租金:"};
/**
* 構造器初始化
*/
public BorrowDialog() {
this.setSize(870, 580);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setLayout(null);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
startLoadData();
}
});
initComponents();
}
/**
* 初始化方法
*/
public void initComponents() {
for(int i=0;i<labs.length;i++){
labs[i] = new JLabel(labelStrs[i],JLabel.RIGHT);
labs[i].setBounds(10,100+50*i,100,30);
this.add(labs[i]);
}
for(int i=0;i<txts.length;i++){
txts[i] = new JTextField();
txts[i].setBounds(110, 100+50*i, 150, 30);
this.add(txts[i]);
}
txts[1].setEnabled(false);
txts[2].setEnabled(false);
txts[4].setEnabled(false);
txts[5].setEnabled(false);
txts[6].setEnabled(false);
readerBtn = new JButton();
readerBtn.setBounds(260, 100, 20, 20);
readerBtn.addActionListener(this);
this.add(readerBtn);
bookBtn = new JButton();
bookBtn.setBounds(260, 250, 20, 20);
bookBtn.addActionListener(this);
this.add(bookBtn);
okBtn = new JButton("确認借出");
okBtn.setBounds(80, 500, 80, 30);
okBtn.addActionListener(this);
this.add(okBtn);
cancleBtn = new JButton("取消借出");
cancleBtn.setBounds(180, 500, 80, 30);
cancleBtn.addActionListener(this);
this.add(cancleBtn);
// 表格内容以及格式設定
dataTable = new JTable();
dataTable.getTableHeader().setReorderingAllowed(false);
dataTable.getTableHeader().setResizingAllowed(true);
dataPane = new JScrollPane(dataTable);
dataPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
dataPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
dataPane.setBounds(330, 100, 470, 350);
this.add(dataPane);
JPanel SouthPanel = new JPanel();
this.add(SouthPanel, BorderLayout.SOUTH);
// 下方按鈕
String[] str = { "首頁", "上一頁", "下一頁", "末頁"};
for (int i = 0; i < chooseButtons.length; i++) {
chooseButtons[i] = new JButton(str[i]);
chooseButtons[i].addActionListener(this);
chooseButtons[i].setFont(NORMAL_FONT);
chooseButtons[i].setBounds(100 + i * 100, 550, 80, 30);
this.add(chooseButtons[i]);
}
hintLabel= new JLabel();
hintLabel.setBounds(100, 450, 200, 30);
hintLabel.setEnabled(false);
this.add(hintLabel);
}
/**
* 方法:重新整理頁面
*/
public void pageComboBoxFlash() {
}
/**
* 方法:主界面獲得資訊資料 并重新整理界面
*
* @return
* @return
*/
public void loadData() {
// 這裡的fNames必須和類裡面的 嚴格對應!!!! 資料庫裡可以忽略大小寫
String[] colNames = { "編号", "讀者編号", "讀者姓名", "書籍編号","書名", "操作員", "借出日期", "是否歸還"};
String[] fNames = { "borrowID", "reader.readerID", "reader.readerName", "book.bookID",
"book.bookName","operatorID", "borrowDate", "isBack"};
// 調用業務邏輯層封裝好的事務腳本
PageBean<BorrowList> bean = bookService.findBorrowList(page,size,Integer.parseInt(txts[0].getText()));
if(bean==null){
JOptionPane.showMessageDialog(null, "此使用者并不存在");
}
else{
List<BorrowList> borrowList = bean.getList();
Object[][] data = new Object[borrowList.size()][colNames.length];
// 反射~~已知對象屬性的名稱 已知對象 通過反射獲得對象屬性的值
for (int i = 0; i < data.length; i++) {
BorrowList temp = borrowList.get(i);
for (int j = 0; j < colNames.length; j++) {
data[i][j] = MyUtil.getValue(temp, fNames[j]);
}
}
// 設定模式,重新整理模式同時重新整理了主界面
TableModel model = new DefaultTableModel(data, colNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
dataTable.setModel(model);
for (int i = 0; i < chooseButtons.length; i++) {
chooseButtons[i].setEnabled(false);
}
if (page > 1) {
chooseButtons[0].setEnabled(true);
chooseButtons[1].setEnabled(true);
}
if (page < totalPage) {
chooseButtons[2].setEnabled(true);
chooseButtons[3].setEnabled(true);
}
}
}
public void startLoadData(){
String[] colNames = { "編号", "讀者編号", "讀者姓名", "書籍編号","書名", "操作員", "借出日期", "是否歸還"};
Object[][] data = new Object[10][colNames.length];
TableModel model = new DefaultTableModel(data, colNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
dataTable.setModel(model);
}
/**
* 重寫監聽器方法
*/
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj == chooseButtons[0]) {
page = 1;
loadData();
} else if (obj == chooseButtons[1]) {
page--;
loadData();
} else if (obj == chooseButtons[2]) {
page++;
loadData();
} else if (obj == chooseButtons[3]) {
page = totalPage;
loadData();
} else if(obj == readerBtn){
Reader reader=readerService.findByKey(Integer.parseInt(txts[0].getText()));
loadData();
txts[1].setText(reader.getReaderName());
txts[2].setText(String.valueOf(reader.getCurrentNumber()));
if(reader.getCurrentNumber()>=reader.getMaxNumber()){
okBtn.setEnabled(false);
hintLabel.setText("該讀者可借書數量已滿!");
}
} else if(obj==bookBtn){
Books book = bookService.findByKey(Integer.parseInt(txts[3].getText()));
txts[4].setText(book.getBookName());
txts[5].setText(String.valueOf(book.getBookNumber()));
txts[6].setText(String.valueOf(book.getRentPerDay()));
if(book.getBookNumber()<=0){
okBtn.setEnabled(false);
hintLabel.setText("該書籍的數量為0!");
}
}else if(obj==okBtn){
bookService.borrow(Integer.parseInt(txts[0].getText()), Integer.parseInt(txts[3].getText()));
loadData();
Reader reader=readerService.findByKey(Integer.parseInt(txts[0].getText()));
Books book = bookService.findByKey(Integer.parseInt(txts[3].getText()));
txts[2].setText(String.valueOf(reader.getCurrentNumber()));
txts[5].setText(String.valueOf(book.getBookNumber()));
}
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new BorrowDialog().setVisible(true);
}
}
7.還書界面
package com.lovo.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import com.lovo.bean.PageBean;
import com.lovo.biz.impl.BooksServiceImpl;
import com.lovo.biz.impl.ReaderServiceImpl;
import com.lovo.entity.Books;
import com.lovo.entity.BorrowList;
import com.lovo.util.MyUtil;
/**
* 查詢資料視窗模型
*
* @author Administrator
*
*/
@SuppressWarnings("serial")
public class bookBackDialog extends JDialog implements ActionListener {
final Font NORMAL_FONT = new Font("微軟雅黑", Font.PLAIN, 16);
final Font BIG_FONT = new Font("微軟雅黑", Font.PLAIN, 70);
private JTable dataTable;
private JScrollPane dataPane;
private int page = 1;
private int size = 20;
private int totalPage = 1;
private int time;
private JLabel readerLabel, bookLabel, hintLabel, moneyLabel, damageLabel;
private JTextField readerField, bookField, hintField, moneyField;
private JButton readerButton, bookButton, okButton, cancelButton;
private JRadioButton yesRadio, noRadio;
private BooksServiceImpl bookService = new BooksServiceImpl();
private ReaderServiceImpl readerService = new ReaderServiceImpl();
/**
* 構造器初始化
*/
public bookBackDialog() {
this.setTitle("歸還書籍");
this.setSize(1000, 580);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setLayout(null);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
startLoadData();
}
});
initComponents();
}
/**
* 初始化方法
*/
public void initComponents() {
readerLabel = new JLabel("請輸入讀者的編号:", JLabel.RIGHT);
readerLabel.setBounds(270, 40, 180, 30);
this.add(readerLabel);
bookLabel = new JLabel("請輸入歸還書籍的編号:", JLabel.RIGHT);
bookLabel.setBounds(270, 100, 180, 30);
this.add(bookLabel);
readerField = new JTextField();
readerField.setBounds(460, 40, 140, 30);
this.add(readerField);
bookField = new JTextField();
bookField.setBounds(460, 100, 140, 30);
this.add(bookField);
readerButton = new JButton();
readerButton.setBounds(600, 50, 20, 20);
readerButton.addActionListener(this);
this.add(readerButton);
bookButton = new JButton();
bookButton.setBounds(600, 110, 20, 20);
bookButton.addActionListener(this);
this.add(bookButton);
// 表格内容以及格式設定
dataTable = new JTable();
dataTable.getTableHeader().setReorderingAllowed(false);
dataTable.getTableHeader().setResizingAllowed(true);
dataPane = new JScrollPane(dataTable);
dataPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
dataPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
dataPane.setBounds(100, 150, 800, 230);
this.add(dataPane);
JPanel SouthPanel = new JPanel();
this.add(SouthPanel, BorderLayout.SOUTH);
damageLabel = new JLabel("書籍是否損壞:", JLabel.RIGHT);
damageLabel.setBounds(200, 390, 140, 30);
this.add(damageLabel);
ButtonGroup bg = new ButtonGroup();
yesRadio = new JRadioButton("是");
noRadio = new JRadioButton("否");
yesRadio.setBounds(340, 390, 50, 30);
noRadio.setBounds(390, 390, 50, 30);
bg.add(yesRadio);
bg.add(noRadio);
this.add(yesRadio);
this.add(noRadio);
hintLabel = new JLabel("超期提示:", JLabel.RIGHT);
hintLabel.setBounds(500, 390, 100, 30);
this.add(hintLabel);
hintField = new JTextField();
hintField.setBounds(600, 390, 140, 30);
hintField.setEditable(false);
this.add(hintField);
moneyLabel = new JLabel("應付金額:", JLabel.RIGHT);
moneyLabel.setBounds(270, 440, 180, 30);
this.add(moneyLabel);
moneyField = new JTextField();
moneyField.setBounds(450, 440, 140, 30);
moneyField.setEditable(false);
this.add(moneyField);
okButton = new JButton("确認歸還");
okButton.setBounds(280, 490, 100, 30);
okButton.addActionListener(this);
this.add(okButton);
cancelButton = new JButton("取消歸還");
cancelButton.setBounds(580, 490, 100, 30);
cancelButton.addActionListener(this);
this.add(cancelButton);
}
/**
* 方法:主界面獲得資訊資料 并重新整理界面
*
* @return
* @return
*/
public void loadData() {
// 這裡的fNames必須和類裡面的 嚴格對應!!!! 資料庫裡可以忽略大小寫
String[] colNames = { "編号", "讀者編号", "讀者姓名", "書籍編号", "書名", "書籍原價",
"借出管理者", "借出日期", "還書日期", "是否歸還", "日租金" };
String[] fNames = { "borrowID", "reader.readerID", "reader.readerName",
"book.bookID", "book.bookName", "book.price", "operatorID",
"borrowDate", "backDate", "isBack", "book.rentPerDay" };
// 調用業務邏輯層封裝好的事務腳本
PageBean<BorrowList> bean = bookService.findBorrowList(totalPage, size,
Integer.parseInt(readerField.getText()));
List<BorrowList> borrowList = bean.getList();
Object[][] data = new Object[borrowList.size()][colNames.length];
// 反射~~已知對象屬性的名稱 已知對象 通過反射獲得對象屬性的值
for (int i = 0; i < data.length; i++) {
BorrowList temp = borrowList.get(i);
for (int j = 0; j < colNames.length; j++) {
data[i][j] = MyUtil.getValue(temp, fNames[j]);
}
}
// 設定模式,重新整理模式同時重新整理了主界面
TableModel model = new DefaultTableModel(data, colNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
dataTable.setModel(model);
}
public void BookloadData() {
// 這裡的fNames必須和類裡面的 嚴格對應!!!! 資料庫裡可以忽略大小寫
String[] colNames = { "編号", "讀者編号", "讀者姓名", "書籍編号", "書名", "書籍原價",
"借出管理者", "借出日期", "還書日期", "是否歸還", "日租金" };
String[] fNames = { "borrowID", "reader.readerID", "reader.readerName",
"book.bookID", "book.bookName", "book.price", "operatorID",
"borrowDate", "backDate", "isBack", "book.rentPerDay" };
// 調用業務邏輯層封裝好的事務腳本
PageBean<BorrowList> bean = bookService.findBorrowListByBook(page,
size, Integer.parseInt(readerField.getText()),
Integer.parseInt(bookField.getText()));
List<BorrowList> borrowList = bean.getList();
Object[][] data = new Object[borrowList.size()][colNames.length];
// 反射~~已知對象屬性的名稱 已知對象 通過反射獲得對象屬性的值
for (int i = 0; i < data.length; i++) {
BorrowList temp = borrowList.get(i);
for (int j = 0; j < colNames.length; j++) {
data[i][j] = MyUtil.getValue(temp, fNames[j]);
}
}
// 設定模式,重新整理模式同時重新整理了主界面
TableModel model = new DefaultTableModel(data, colNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
dataTable.setModel(model);
}
public void startLoadData() {
String[] colNames = { "編号", "讀者編号", "讀者姓名", "書籍編号", "書名", "書籍原價",
"借出管理者", "借出日期", "還書日期", "是否歸還", "日租金" };
Object[][] data = new Object[10][colNames.length];
TableModel model = new DefaultTableModel(data, colNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
dataTable.setModel(model);
}
/**
* 重寫監聽器方法
*/
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj == readerButton) {
loadData();
} else if (obj == bookButton) {
BookloadData();
BorrowList blist = bookService.findTwoKey(
Integer.parseInt(readerField.getText()),
Integer.parseInt(bookField.getText()));
if (blist == null) {
JOptionPane.showMessageDialog(null, "沒有未還的這本書");
} else {
double money = 0.0;
time = (int) ((System.currentTimeMillis() - blist
.getBorrowDate()) / (3600 * 24 * 1000));
if (time <= 30) {
hintField.setText("未超期");
if (yesRadio.isSelected()) {
money = blist.getBook().getPrice();
} else if (noRadio.isSelected()) {
money = 0.0;
}
} else {
hintField.setText("超期" + (time - 30));
if (yesRadio.isSelected()) {
money = blist.getBook().getPrice()
+ blist.getBook().getRentPerDay()
* (time - 30)
* blist.getReader().getReaderType()
.getDisciunt();
} else {
money = blist.getBook().getRentPerDay()
* (time - 30)
* blist.getReader().getReaderType()
.getDisciunt();
;
}
}
moneyField.setText(String.valueOf(money));
if (yesRadio.isSelected()) {
money = blist.getBook().getPrice();
}
}
} else if (obj == okButton) {
bookService.bookBack(Integer.parseInt(readerField.getText()),
Integer.parseInt(bookField.getText()));
loadData();
}
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new bookBackDialog().setVisible(true);
}
}