使用swing做的熟悉控件使用的DEMO
源代码在线查看: booklist.java
package book; import java.util.HashSet; import java.util.Iterator; import java.util.Collection; import java.util.ArrayList; import userexception.*; /** * class BookList */ public class BookList { private static BookList instance = new BookList(); private HashSet books = null; private int booknum; //constructor private BookList() { booknum = 1; books = new HashSet(); try { addBook(new Book(booknum++, "Ten Years", "Kit", Book.COMPUTER, 30.00, "China")); addBook(new Book(booknum++, "Red And Black", "Unknown", Book.COMPUTER, 30.00, "People")); addBook(new Book(booknum++, "C Programming", "Kit", Book.COMPUTER, 30.00, "China")); addBook(new Book(booknum++, "Three Pigs", "Tom", Book.NONCOMPUTER, 34.00, "Family")); } catch (AddException e) { } } //static methods to get the instance public static BookList getInstance() { return instance; } //get the books public HashSet getBooks() { return books; } //add a book public void addBook(Book bk) throws AddException { if(! books.add(bk)) throw new AddException(); } //find books public Collection query(String name, String author, int cat, String from) throws BookNotFoundException{ ArrayList result = new ArrayList(); Book tmpBook = null; Iterator i = books.iterator(); while (i.hasNext()) { tmpBook = (Book)i.next(); if(!name.equals("")) { if(! tmpBook.getName().equals(name)) continue; } if(!author.equals("")) { if(! tmpBook.getAuthor().equals(author)) continue; } if(!(cat < 0)) { if(! (tmpBook.getBookType() == cat)) continue; } if(!from.equals("")) { if(! tmpBook.getFrom().equals(from)) continue; } System.out.println(tmpBook); result.add(tmpBook); } if(result.size() == 0) throw new BookNotFoundException(); return result; } //unique search by bookid public Book queryById (int bookid) throws BookNotFoundException { Iterator i = books.iterator(); Book temp = null; while (i.hasNext()) { temp = (Book)i.next(); if(temp.getBookId() == bookid) { break; } } if(temp == null) throw new BookNotFoundException(); return temp; } //modify a book public void modifyBook(Book bk) throws BookNotFoundException { Book old = queryById(bk.getBookId()); /* if( old != null) { books.remove(old); books.add(bk); } */ old.setName(bk.getName()); old.setAuthor(bk.getAuthor()); old.setBookType(bk.getBookType()); old.setCost(bk.getCost()); old.setFrom(bk.getFrom()); } //make unique number for the new book public int makeNo() { return booknum++; } }