package com.lovo.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 书(最核心的业务实体)
*
* @author Administrator
* @version 1.0
* @created 05-十一月-2014 15:37:30
*/
public class Book {
/**
* 一天有多少毫秒
*/
public static final long MILLIS_OF_THE_DAY = 24 * 60 * 60 * 1000;
private String isbn; // 编号
private String name; // 名称
private double price; // 日租金
private boolean lended; // 是否借出
private long lendDate; // 借出日期
private int counter; // 借出次数
/**
* 构造器
* @param isbn 编号
* @param name 名称
* @param price 日租金
*/
public Book(String isbn, String name, double price, int counter) {
this.isbn = isbn;
this.name = name;
this.price = price;
this.counter = counter;
}
/**
* 借出
* @return 借出成功返回true否则返回false
*/
public boolean lendOut() {
if(!lended) {
lended = true;
lendDate = System.currentTimeMillis();
counter++;
return true;
}
return false;
}
/**
* 归还
* @return 返回需要缴纳的租金
*/
public double returnBack() {
if(lended) {
lended = false;
long currentTime = System.currentTimeMillis();
int days = (int) Math.ceil((currentTime - lendDate) / (double)MILLIS_OF_THE_DAY);
lendDate = 0;
return days * price;
}
return 0.0;
}
public int getCounter() {
return counter;
}
public String getIsbn() {
return isbn;
}
/**
* 返回借出日期
* @return 借出日期的字符串
*/
public String getLendDate() {
if(lendDate == 0) {
return "---";
}
else {
Date date = new Date(lendDate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
return sdf.format(date);
}
}
public boolean isLended() {
return lended;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setCounter(int counter) {
this.counter = counter;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
}
package com.lovo.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("serial")
// POJO
public class User implements Serializable {
private String username;
private String password;
private boolean gender;
private List<String> favorites = new ArrayList<String>(0);
private String nationality;
private String email;
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public List<String> getFavorites() {
return favorites;
}
public void addFavorite(String favorite) {
favorites.add(favorite);
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password
+ ", gender=" + gender + ", favorites=" + favorites
+ ", nationality=" + nationality + ", email=" + email + "]";
}
}
package com.lovo.ui;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import com.lovo.entity.Book;
import com.lovo.util.MyUtil;
@SuppressWarnings("serial")
public class AddDialog extends JDialog {
private static String[] itemNames = {"编号", "书名", "日租金"};
private JLabel[] itemLabels = new JLabel[itemNames.length];
private JTextField isbnField, nameField;
private JSpinner priceSpinner;
private JButton addButton, resetButton;
private ShowBookFrame parent = null;
public AddDialog(ShowBookFrame parent) {
this.parent = parent;
this.setModal(true); // 设置窗口为模态对话框
this.setTitle("新增书籍");
this.setSize(270, 300);
this.setResizable(false);
this.setLocationRelativeTo(parent);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); // 关闭窗口销毁窗口
initComponents();
}
private void initComponents() {
this.setLayout(null);
for(int i = 0; i < itemLabels.length; i++) {
itemLabels[i] = new JLabel(itemNames[i] + ":", JLabel.RIGHT);
itemLabels[i].setBounds(10, 30 + 60 * i, 60, 40);
this.add(itemLabels[i]);
}
isbnField = new JTextField(10);
isbnField.setBounds(80, 35, 100, 30);
this.add(isbnField);
nameField = new JTextField(20);
nameField.setBounds(80, 95, 150, 30);
this.add(nameField);
SpinnerModel sModel = new SpinnerNumberModel(1.0, 0.1, 5.0, 0.1);
priceSpinner = new JSpinner(sModel);
priceSpinner.setBounds(80, 155, 40, 30);
this.add(priceSpinner);
addButton = new JButton("添加");
addButton.setBounds(55, 220, 60, 30);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String isbn = isbnField.getText().trim();
String name = nameField.getText().trim();
String priceStr = String.format("%.1f", priceSpinner.getValue());
double price = Double.parseDouble(priceStr);
AddDialog.this.dispose();
Book temp = new Book(isbn, name, price, 0);
parent.getBookManager().add(temp);
parent.refreshTableModel();
}
});
this.add(addButton);
resetButton = new JButton("重置");
resetButton.setBounds(155, 220, 60, 30);
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(Component comp : getContentPane().getComponents()) {
MyUtil.resetComponent(comp);
}
priceSpinner.setValue(1);
}
});
this.add(resetButton);
MyUtil.setFontForContainer(new Font("微软雅黑", Font.PLAIN, 12), this.getContentPane());
}
}
package com.lovo.ui;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import com.lovo.util.MyUtil;
@SuppressWarnings("serial")
public class DeleteDialog extends JDialog {
private static String[] itemNames = {"编号", "书名"};
private JLabel[] itemLabels = new JLabel[itemNames.length];
private JTextField isbnField, nameField;
private JButton deleteButton, resetButton;
private ShowBookFrame parent = null;
public DeleteDialog(ShowBookFrame parent) {
this.parent = parent;
this.setModal(true); // 设置窗口为模态对话框
this.setTitle("删除书籍");
this.setSize(270, 300);
this.setResizable(false);
this.setLocationRelativeTo(parent);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); // 关闭窗口销毁窗口
initComponents();
}
private void initComponents() {
this.setLayout(null);
for(int i = 0; i < itemLabels.length; i++) {
itemLabels[i] = new JLabel(itemNames[i] + ":", JLabel.RIGHT);
itemLabels[i].setBounds(10, 30 + 60 * i, 60, 40);
this.add(itemLabels[i]);
}
isbnField = new JTextField(10);
isbnField.setBounds(80, 35, 100, 30);
isbnField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
String isbn = isbnField.getText().trim();
if (parent.getBookManager().findByISBN(isbn) != null) {
nameField.setText(parent.getBookManager().findByISBN(isbn).getName());
}else{
nameField.setText("未找到对应书籍!");
}
}
@Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
}
});
this.add(isbnField);
nameField = new JTextField(20);
nameField.setBounds(80, 95, 150, 30);
this.add(nameField);
deleteButton = new JButton("删除");
deleteButton.setBounds(55, 220, 60, 30);
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String isbn = isbnField.getText().trim();
parent.getBookManager().deleteByISBN(isbn);
DeleteDialog.this.dispose();
parent.refreshTableModel();
}
});
this.add(deleteButton);
resetButton = new JButton("重置");
resetButton.setBounds(155, 220, 60, 30);
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(Component comp : getContentPane().getComponents()) {
MyUtil.resetComponent(comp);
}
}
});
this.add(resetButton);
MyUtil.setFontForContainer(new Font("微软雅黑", Font.PLAIN, 12), this.getContentPane());
}
}
package com.lovo.ui;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.lovo.biz.BookManager;
import com.lovo.entity.Book;
import com.lovo.util.MyUtil;
@SuppressWarnings("serial")
public class ShowBookFrame extends JFrame {
private BookManager manager = new BookManager(); // 创建书籍管理器对象
private JTable bookTable = null; // 定义表格控件的引用
private JButton addButton, delButton, updateButton;
private static String[] columnNames = {"编号", "书名", "价格", "状态", "借出日期", "借出次数"};
public ShowBookFrame() {
this.setTitle("查看书籍信息");
this.setSize(600, 400);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
initComponents(); // 初始化窗口中的控件
}
public BookManager getBookManager() {
return manager;
}
public void refreshTableModel() {
if(bookTable != null) {
List<Book> list = manager.findAll(); // 调用业务逻辑方法findAll查找所有图书
Object[][] data = new Object[list.size()][columnNames.length];
for(int i = 0; i < data.length; i++) {
Book temp = list.get(i);
data[i][0] = temp.getIsbn();
data[i][1] = temp.getName();
data[i][2] = temp.getPrice();
data[i][3] = temp.isLended()? "已借出" : "未借出";
data[i][4] = temp.getLendDate();
data[i][5] = temp.getCounter();
}
bookTable.setModel(new DefaultTableModel(data, columnNames) {
@Override
public boolean isCellEditable(int row, int column) { // 不允许编辑单元格
return false;
}
});
}
}
private void initComponents() {
bookTable = new JTable();
// 设置表头不能够重新排列
bookTable.getTableHeader().setReorderingAllowed(false);
refreshTableModel();
this.add(new JScrollPane(bookTable)); // 为表格添加滚动条后再加入到窗口中(这样才能显示表头)
JPanel buttonPanel = new JPanel();
addButton = new JButton("新增图书");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new AddDialog(ShowBookFrame.this).setVisible(true);
}
});
delButton = new JButton("删除图书");
delButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new DeleteDialog(ShowBookFrame.this).setVisible(true);
}
});
updateButton = new JButton("修改图书");
updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new UpdateDialog(ShowBookFrame.this).setVisible(true);
}
});
buttonPanel.add(addButton);
buttonPanel.add(delButton);
buttonPanel.add(updateButton);
this.add(buttonPanel, BorderLayout.SOUTH);
Font font = new Font("微软雅黑", Font.PLAIN, 14);
MyUtil.setFontForContainer(font, buttonPanel);
}
public static void main(String[] args) {
new ShowBookFrame().setVisible(true);
}
}
package com.lovo.ui;
import java.awt.Component;
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 javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
import com.lovo.entity.User;
import com.lovo.util.MyUtil;
@SuppressWarnings("serial")
// 事件绑定有三种方式:
// 1. 让主类实现接口并重写事件回调方法
// 2. 匿名内部类(就地实例化接口)
// 3. 内部类(内部类可以访问外部类的所有成员)
public class RegFrame extends JFrame {
// 自定义内部类作为监听器
private class ButtonHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == regButton) { // 处理用户点击注册按钮
String username = usernameField.getText().trim();
if(username.matches("[a-zA-Z]\\w{5,19}")) {
String password = new String(passwordField.getPassword());
String rePassword = new String(rePasswordField.getPassword());
if(password.length() > 0) {
if(password.equals(rePassword)) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setGender(maleRadioButton.isSelected());
for(int i = 0; i < favCheckBoxes.length; i++) {
if(favCheckBoxes[i].isSelected()) {
user.addFavorite(favNames[i]);
}
}
user.setNationality(provComboBox.getSelectedItem().toString() +
cityComboBox.getSelectedItem().toString());
user.setEmail(emailField.getText().trim());
System.out.println(user);
}
else {
JOptionPane.showMessageDialog(null, "两次密码不一致!", "错误", JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(null, "密码不能为空!", "错误", JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(null, "无效的用户名!", "错误", JOptionPane.ERROR_MESSAGE);
}
}
else if(source == resetButton) { // 处理用户点击重置按钮
for(Component c : getContentPane().getComponents()) {
MyUtil.resetComponent(c); // 调用封装的工具类的工具方法实现控件的重置
}
maleRadioButton.setSelected(true); // 默认性别为男
}
}
}
// 定义窗口上需要的控件(component)
private static String[] hintNames = {"用户名", "密码", "确认密码", "性别", "爱好", "籍贯", "邮箱"};
private JLabel[] hintLabels = new JLabel[hintNames.length]; // 标签数组
private JTextField usernameField, emailField; // 输入用户名和邮箱的文本框
private JPasswordField passwordField, rePasswordField; // 输入密码和确认密码的密码框
private JRadioButton maleRadioButton, femaleRadioButton; // 性别的单选按钮
private static String[] favNames = {"旅游", "看书", "游戏", "汽车"};
private JCheckBox[] favCheckBoxes = new JCheckBox[favNames.length]; // 爱好的复选框
private static String[] provNames = {"北京", "四川省", "广东省", "广西省"};
private static String[][] cityNames = {
{"东城区", "西城区", "朝阳区", "宣武区", "石景山区"}, {"成都", "绵阳", "德阳"},
{"广州", "肇庆", "深圳", "惠州", "江门"}, {"南宁", "柳州", "北海", "百色"}
};
private JComboBox<String> provComboBox, cityComboBox; // 省和市的下拉列表
private JButton regButton, resetButton; // 注册和重置按钮
public RegFrame() {
this.setTitle("用户注册");
this.setSize(400, 600);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
initComponents();
}
// initialize components (初始化窗口控件)
private void initComponents() {
this.setLayout(null); // 不使用默认的BorderLayout布局管理器
for(int i = 0; i < hintLabels.length; i++) {
hintLabels[i] = new JLabel(hintNames[i] + ":", JLabel.RIGHT); // 初始化标签(文字右对齐)
hintLabels[i].setBounds(35, 50 + 60 * i, 60, 40);
this.add(hintLabels[i]);
}
usernameField = new JTextField(20);
usernameField.setBounds(135, 55, 150, 30);
this.add(usernameField);
passwordField = new JPasswordField(20);
passwordField.setBounds(135, 115, 150, 30);
this.add(passwordField);
rePasswordField = new JPasswordField(20);
rePasswordField.setBounds(135, 175, 150, 30);
this.add(rePasswordField);
maleRadioButton = new JRadioButton("男", true);
maleRadioButton.setBounds(135, 235, 60, 30);
this.add(maleRadioButton);
femaleRadioButton = new JRadioButton("女");
femaleRadioButton.setBounds(205, 235, 60, 30);
this.add(femaleRadioButton);
// 放在同一个按钮组中的单选按钮才能实现互斥的选择
ButtonGroup genderButtonGroup = new ButtonGroup();
genderButtonGroup.add(maleRadioButton);
genderButtonGroup.add(femaleRadioButton);
for(int i = 0; i < favCheckBoxes.length; i++) {
favCheckBoxes[i] = new JCheckBox(favNames[i]);
favCheckBoxes[i].setBounds(135 + 60 * i, 295, 60, 30);
this.add(favCheckBoxes[i]);
}
provComboBox = new JComboBox<String>(provNames);
provComboBox.setBounds(135, 355, 80, 30);
provComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int index = provComboBox.getSelectedIndex();
String[] cities = cityNames[index];
// Swing是基于MVC架构的
// 要修改显示的数据只需要调用setModel方法更新模型即可
// 当模型改变的时候界面自动刷新
cityComboBox.setModel(new DefaultComboBoxModel<String>(cities));
}
});
this.add(provComboBox);
cityComboBox = new JComboBox<String>(cityNames[0]);
cityComboBox.setBounds(235, 355, 80, 30);
this.add(cityComboBox);
emailField = new JTextField(30);
emailField.setBounds(135, 415, 200, 30);
this.add(emailField);
ActionListener buttonHandler = new ButtonHandler(); // 创建自定义监听器对象
regButton = new JButton("注册");
regButton.setBounds(100, 500, 80, 30);
regButton.addActionListener(buttonHandler);
this.add(regButton);
resetButton = new JButton("重置");
resetButton.setBounds(220, 500, 80, 30);
resetButton.addActionListener(buttonHandler);
this.add(resetButton);
Font defaultFont = new Font("微软雅黑", Font.PLAIN, 14);
MyUtil.setFontForContainer(defaultFont, this.getContentPane());
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new RegFrame().setVisible(true);
}
}
package com.lovo.ui;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import com.lovo.util.MyUtil;
@SuppressWarnings("serial")
public class UpdateDialog extends JDialog {
private static String[] itemNames = {"编号", "书名", "修改价格"};
private JLabel[] itemLabels = new JLabel[itemNames.length];
private JTextField isbnField, nameField, priceField;
private JButton updateButton, resetButton;
private ShowBookFrame parent = null;
public UpdateDialog(ShowBookFrame parent) {
this.parent = parent;
this.setModal(true); // 设置窗口为模态对话框
this.setTitle("修改书籍");
this.setSize(270, 300);
this.setResizable(false);
this.setLocationRelativeTo(parent);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); // 关闭窗口销毁窗口
initComponents();
}
private void initComponents() {
this.setLayout(null);
for(int i = 0; i < itemLabels.length; i++) {
itemLabels[i] = new JLabel(itemNames[i] + ":", JLabel.RIGHT);
itemLabels[i].setBounds(10, 30 + 60 * i, 60, 40);
this.add(itemLabels[i]);
}
isbnField = new JTextField(10);
isbnField.setBounds(80, 35, 100, 30);
isbnField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
String isbn = isbnField.getText().trim();
if (parent.getBookManager().findByISBN(isbn) != null) {
nameField.setText(parent.getBookManager().findByISBN(isbn).getName());
priceField.setText("原价为:" + parent.getBookManager().findByISBN(isbn).getPrice());
}else{
nameField.setText("未找到对应书籍!");
}
}
@Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
}
});
this.add(isbnField);
nameField = new JTextField(20);
nameField.setBounds(80, 95, 100, 30);
this.add(nameField);
priceField = new JTextField(20);
priceField.setBounds(80, 155, 100, 30);
priceField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
@Override
public void focusGained(FocusEvent e) {
priceField.setText("");
}
});
this.add(priceField);
updateButton = new JButton("修改");
updateButton.setBounds(55, 220, 60, 30);
updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String isbn = isbnField.getText().trim();
double price = Double.parseDouble(priceField.getText().trim());
parent.getBookManager().findByISBN(isbn).setPrice(price);
UpdateDialog.this.dispose();
parent.refreshTableModel();
}
});
this.add(updateButton);
resetButton = new JButton("重置");
resetButton.setBounds(155, 220, 60, 30);
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(Component comp : getContentPane().getComponents()) {
MyUtil.resetComponent(comp);
}
}
});
this.add(resetButton);
MyUtil.setFontForContainer(new Font("微软雅黑", Font.PLAIN, 12), this.getContentPane());
}
}
package com.lovo.util;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class MyUtil {
private MyUtil() {}
public static void resetComponent(Component comp) {
if(comp instanceof JTextField) {
((JTextField) comp).setText("");
}
else if(comp instanceof JPasswordField) {
((JPasswordField) comp).setText("");
}
else if(comp instanceof JComboBox) {
((JComboBox<?>) comp).setSelectedIndex(0);
}
else if(comp instanceof JCheckBox) {
((JCheckBox) comp).setSelected(false);
}
}
public static void setFontForContainer(Font font, Container container) {
for(Component comp : container.getComponents()) {
comp.setFont(font);
}
}
public static void setFontForComponent(Font font, Component comp) {
comp.setFont(font);
}
}