Javaswing mysql
包名:Work
class Main
package Work;
//函数入口,调用登录界面函数
public class Main {
public static void main(String[] args) throws Exception {
//数据库地址
String str = "jdbc:mysql://localhost:3306/bookUIData?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT";
String id = "root";
String password = "root";
DataBase dataBase = new DataBase(str, id, password);
new Login(dataBase);
}
}
class Login
package Work;
//登录界面类
//bug:注册账号,修改密码后需要重新登陆才能登录,因为用户集合未刷新
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
public class Login extends JFrame {
DataBase dataBase;
ArrayList<User> userList;
Timer timer;
public Login(DataBase dataBase) throws Exception {
this.dataBase = dataBase;
this.userList = dataBase.getUserList();
//先放置控件
setComponent();
//放入事件监听函数
setActionListen();
//最后布置页面(先布置页面会覆盖控件布置)
loginFrame();
timer = new Timer(0, E -> {
StringBuffer sBuffer = new StringBuffer();
//时分秒
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
//这样获取的月份是从0开始的
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
sBuffer.append(String.format("%04d", year)).append("年").append(month).append("月").append(day).append("日 ").append(String.format("%02d", hour)).append(":").append(String.format("%02d", minute)).append(":").append(String.format("%02d", second));
timeLabel.setText(sBuffer.toString());
});
timer.start();
}
//页面属性设置
public void loginFrame(){
//设置窗口的参数
setBounds(500,300,600,400);
//禁用重新调整窗口大小的功能
setResizable(false);
//关闭窗口的右上角的叉的同时关闭程序
setDefaultCloseOperation(EXIT_ON_CLOSE);
//设置窗口上当前程序的名字
setTitle("图书管理系统--登录页面");
//清除默认的布局管理器
getContentPane().setLayout(null);
//设置窗口显示
setVisible(true);
}
//定义控件
JButton loginButton, restartButton, insertButton, changeButton;
JLabel idLabel, pwdLabel, titleLabel, timeLabel;
JTextField idText;
JPasswordField pwdText;
//控件集合
ArrayList<JComponent> listComponent = new ArrayList<>();
//页面控件布置
public void setComponent(){
//文本输入框(以及密码输入框)
idText = new JTextField();
pwdText = new JPasswordField();
//设置位置(左上角坐标)与宽高
idText.setBounds(200, 110, 200, 45);
pwdText.setBounds(200, 175, 200, 45);
//存入集合
listComponent.add(idText);
listComponent.add(pwdText);
//放到页面上
getContentPane().add(idText);
getContentPane().add(pwdText);
//标签
idLabel = new JLabel("账号:");
pwdLabel = new JLabel("密码:");
titleLabel = new JLabel("图书管理系统");
timeLabel = new JLabel();
//设置坐标与宽高
idLabel.setBounds(130, 110, 60, 45);
pwdLabel.setBounds(130, 175, 60, 45);
titleLabel.setBounds(225, 50, 200, 60);
timeLabel.setBounds(5, 320, 305, 40);
//存入集合
listComponent.add(idLabel);
listComponent.add(pwdLabel);
listComponent.add(timeLabel);
//titleLabel不存入集合单独设置
titleLabel.setFont(new Font("黑体", Font.BOLD, 24));
//放到页面上
getContentPane().add(idLabel);
getContentPane().add(pwdLabel);
getContentPane().add(titleLabel);
getContentPane().add(timeLabel);
//按钮
loginButton = new JButton("登录");
restartButton = new JButton("重置");
insertButton = new JButton("注册");
changeButton = new JButton("改密");
/*
//事件监听
loginButton.addActionListener(this);
restartButton.addActionListener(this);
insertButton.addActionListener(this);
changeButton.addActionListener(this);
*/
//设置大小
loginButton.setBounds(210, 240, 80, 40);
restartButton.setBounds(310, 240, 80, 40);
insertButton.setBounds(405, 112, 80, 40);
changeButton.setBounds(405, 177, 80, 40);
//存入集合
listComponent.add(loginButton);
listComponent.add(restartButton);
listComponent.add(insertButton);
listComponent.add(changeButton);
//放置于页面
getContentPane().add(loginButton);
getContentPane().add(restartButton);
getContentPane().add(insertButton);
getContentPane().add(changeButton);
//整体设置字体
for (JComponent jComponent : listComponent) {
jComponent.setFont(new Font("宋体", Font.BOLD, 20));
}
}
/*
@Override
public void actionPerformed(ActionEvent e) {
//给回车键增加按钮监听事件(登录按钮)
this.getRootPane().setDefaultButton(loginButton);
if(e.getSource() == loginButton){
boolean flag = false;
for (User user : userList) {
//找到账号
if (user.getId().equals(idText.getText())) {
//密码符合
if (user.getPwd().equals(pwdText.getText())) {
//登录成功(后续注释掉)
//创建新页面
try {
new Menu(dataBase);
} catch (Exception E) {
E.printStackTrace();
}
//跳转页面后(创建新页面),关闭此页面
dispose();
} else {
JOptionPane.showMessageDialog(getContentPane(), "密码有误!");
}
flag = true;
}
}
//账号不符
if (!flag) {
JOptionPane.showMessageDialog(getContentPane(), "账号有误!");
}
}else if(e.getSource() == restartButton){
idText.setText("");
pwdText.setText("");
}else if(e.getSource() == insertButton){
new Id(true, dataBase);
this.userList = this.dataBase.getUserList();
}else if(e.getSource() == changeButton){
new Id(false, dataBase);
this.userList = this.dataBase.getUserList();
}
}*/
//事件监听
public void setActionListen(){
//给回车键增加按钮监听事件(登录按钮)
this.getRootPane().setDefaultButton(loginButton);
//登录按钮监听
loginButton.addActionListener(e -> {
boolean flag = false;
for (User user : userList) {
//找到账号
if (user.getId().equals(idText.getText())) {
//密码符合
if (user.getPwd().equals(pwdText.getText())) {
//登录成功(后续注释掉)
//创建新页面
try {
new Menu(dataBase);
} catch (Exception E) {
E.printStackTrace();
}
//跳转页面后(创建新页面),关闭此页面
dispose();
} else {
JOptionPane.showMessageDialog(getContentPane(), "密码有误!");
}
flag = true;
}
}
//账号不符
if (!flag) {
JOptionPane.showMessageDialog(getContentPane(), "账号有误!");
}
});
//重置按钮监听
restartButton.addActionListener(e -> {
idText.setText("");
pwdText.setText("");
});
//注册按钮
insertButton.addActionListener(e -> {
DataBase dataBase1 = dataBase;
new Id(true, dataBase1);
});
//修改密码按钮
changeButton.addActionListener(e -> {
DataBase dataBase1 = dataBase;
new Id(false, dataBase1);
});
}
}
class Id
package Work;
//账号注册或者修改密码
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class Id extends JFrame {
JButton submitButton, cancelButton;
JLabel idLabel, pwdLabel, firstPwdLabel, secondPwdLabel;
JTextField idText, pwdText, firstPwdText, secondPwdText;
ArrayList<JComponent> componentsList = new ArrayList<>();
DataBase dataBase;
ArrayList<User> userList;
public Id(boolean flag, DataBase dataBase) {
this.dataBase = dataBase;
this.userList = dataBase.getUserList();
if(flag){
insertUser();
}else {
changeUser();
}
}
public void insertUser(){
//设置窗口的参数
setBounds(500,300,400,300);
//禁用重新调整窗口大小的功能
setResizable(false);
//关闭窗口的右上角
//设置窗口上当前程序的名字
setTitle("图书管理系统--注册账号");
//清除默认的布局管理器
getContentPane().setLayout(null);
//设置窗口显示
setVisible(true);
idLabel = new JLabel("账号:");
pwdLabel = new JLabel("密码:");
firstPwdLabel = new JLabel("重复:");
secondPwdLabel = new JLabel("重复:");
componentsList.add(idLabel);
componentsList.add(pwdLabel);
componentsList.add(firstPwdLabel);
componentsList.add(secondPwdLabel);
idLabel.setBounds(20, 0, 80, 40);
pwdLabel.setBounds(20, 40, 80, 40);
firstPwdLabel.setBounds(20, 80, 80, 40);
secondPwdLabel.setBounds(20, 120, 80, 40);
add(idLabel);
add(pwdLabel);
add(firstPwdLabel);
add(secondPwdLabel);
idText = new JTextField();
pwdText = new JTextField();
firstPwdText = new JTextField();
secondPwdText = new JTextField();
componentsList.add(idText);
componentsList.add(pwdText);
componentsList.add(firstPwdText);
componentsList.add(secondPwdText);
idText.setBounds(85, 5, 240, 35);
pwdText.setBounds(85, 45, 240, 35);
firstPwdText.setBounds(85, 85, 240, 35);
secondPwdText.setBounds(85, 125, 240, 35);
add(idText);
add(pwdText);
add(firstPwdText);
add(secondPwdText);
submitButton = new JButton("确定");
cancelButton = new JButton("取消");
componentsList.add(submitButton);
componentsList.add(cancelButton);
submitButton.setBounds(100, 180, 80, 40);
cancelButton.setBounds(200, 180, 80, 40);
add(submitButton);
add(cancelButton);
for (JComponent jComponent : componentsList) {
jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 20));
}
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean flag = true;
if(idText.getText().equals("") || pwdText.getText().equals("")){
flag = false;
JOptionPane.showMessageDialog(getContentPane(), "账号密码不能为空!");
}
if(flag){
for (User user : userList) {
if(user.getId().equals(idText.getText())){
flag = false;
JOptionPane.showMessageDialog(getContentPane(), "id重复!");
}
}
}
if (flag){
if(pwdText.getText().equals(firstPwdText.getText()) && pwdText.getText().equals(secondPwdText.getText())){
dataBase.insertUser(idText.getText(), pwdText.getText());
JOptionPane.showMessageDialog(getContentPane(), "注册成功!");
dispose();
JOptionPane.showMessageDialog(getContentPane(), "注册成功后,请重启程序!");
} else {
JOptionPane.showMessageDialog(getContentPane(), "三次密码不一致!");
}
}
}
});
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(getContentPane(), "已经取消!");
dispose();
}
});
}
public void changeUser(){
//设置窗口的参数
setBounds(500,300,400,300);
//禁用重新调整窗口大小的功能
setResizable(false);
//关闭窗口的右上角
//设置窗口上当前程序的名字
setTitle("图书管理系统--注册账号");
//清除默认的布局管理器
getContentPane().setLayout(null);
//设置窗口显示
setVisible(true);
idLabel = new JLabel("账号:");
pwdLabel = new JLabel("原密:");
firstPwdLabel = new JLabel("新密:");
secondPwdLabel = new JLabel("重复:");
componentsList.add(idLabel);
componentsList.add(pwdLabel);
componentsList.add(firstPwdLabel);
componentsList.add(secondPwdLabel);
idLabel.setBounds(20, 0, 80, 40);
pwdLabel.setBounds(20, 40, 80, 40);
firstPwdLabel.setBounds(20, 80, 80, 40);
secondPwdLabel.setBounds(20, 120, 80, 40);
add(idLabel);
add(pwdLabel);
add(firstPwdLabel);
add(secondPwdLabel);
idText = new JTextField();
pwdText = new JTextField();
firstPwdText = new JTextField();
secondPwdText = new JTextField();
componentsList.add(idText);
componentsList.add(pwdText);
componentsList.add(firstPwdText);
componentsList.add(secondPwdText);
idText.setBounds(85, 5, 240, 35);
pwdText.setBounds(85, 45, 240, 35);
firstPwdText.setBounds(85, 85, 240, 35);
secondPwdText.setBounds(85, 125, 240, 35);
add(idText);
add(pwdText);
add(firstPwdText);
add(secondPwdText);
submitButton = new JButton("确定");
cancelButton = new JButton("取消");
componentsList.add(submitButton);
componentsList.add(cancelButton);
submitButton.setBounds(100, 180, 80, 40);
cancelButton.setBounds(200, 180, 80, 40);
add(submitButton);
add(cancelButton);
for (JComponent jComponent : componentsList) {
jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 20));
}
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean flag = false;
for (User user : userList) {
if(user.getId().equals(idText.getText())){
if(user.getPwd().equals(pwdText.getText())){
if(firstPwdText.getText().equals(secondPwdText.getText())){
dataBase.changeUser(user.getId(), firstPwdText.getText());
JOptionPane.showMessageDialog(getContentPane(), "修改成功!");
dispose();
JOptionPane.showMessageDialog(getContentPane(), "修改密码后,请重启程序!");
}else {
JOptionPane.showMessageDialog(getContentPane(), "两次密码不一致!");
}
}else {
JOptionPane.showMessageDialog(getContentPane(), "密码错误!");
}
flag = true;
}
}
if (!flag){
JOptionPane.showMessageDialog(getContentPane(), "账号不存在!");
}
}
});
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(getContentPane(), "已经取消!");
dispose();
}
});
}
}
class Menu
package Work;
//主界面类
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
public class Menu extends JFrame implements ActionListener {
//组件
JTextField searchText;//查询文本框
JLabel TimeLabel;//时间显示标签
JButton searchButton, demoButton, insertButton,//查询按钮,导入按钮,插入按钮
moneySortUpButton, moneySortDownButton, sortButton,//升序按钮,降序按钮,刷新(顺序)按钮
deleteButton, changeButton;//删除按钮,修改按钮
JTable bookTable;
JScrollPane scrollPane;
DataBase dataBase;
TableModel tableModel;
ArrayList<JComponent> list = new ArrayList<>();
//定时器,用于刷新页面时间
Timer timer;
//构造方法
public Menu(DataBase dataBase) throws Exception {
this.dataBase = dataBase;
this.tableModel= new TableModel(dataBase);
//控件布置
setComponent();
//直接给控件添加事件监听,无需在此调用监听函数
//页面布置
menuFrame();
timer = new Timer(0, E -> {
StringBuffer sBuffer = new StringBuffer();
//时分秒
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
//这样获取的月份是从0开始的
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
sBuffer.append(String.format("%04d", year)).append("年").append(month).append("月").append(day).append("日 ").append(String.format("%02d", hour)).append(":").append(String.format("%02d", minute)).append(":").append(String.format("%02d", second));
TimeLabel.setText(sBuffer.toString());
});
timer.start();
}
//图形界面设置
public void menuFrame(){
//设置大小
setBounds(200, 100, 1200, 800);
//设置关闭
setDefaultCloseOperation(EXIT_ON_CLOSE);
//设置不可调节大小
setResizable(false);
//设置名称
setTitle("图书管理系统--表格");
//清除默认布局
getContentPane().setLayout(null);
//设置显示
setVisible(true);
}
//组件布置
public void setComponent(){
bookTable = new JTable(tableModel);
//表头字体设置
bookTable.getTableHeader().setFont(new Font("黑体", Font.BOLD, 20));
bookTable.getTableHeader().setForeground(Color.RED);
//表格字体设置
bookTable.setFont(new Font("微软雅黑", Font.PLAIN, 15));
bookTable.setForeground(Color.BLACK);
//线条设置
bookTable.setGridColor(Color.BLACK);
//表格宽度设置
bookTable.setRowHeight(50);
//表格大小设置
bookTable.setBounds(200, 80, 800, 600);
//多行选择设置
bookTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//表头进制移动设置
bookTable .getTableHeader().setReorderingAllowed(false);
scrollPane = new JScrollPane(bookTable);
scrollPane.setBounds(150, 80, 900, 600);
add(scrollPane);
searchButton = new JButton("查询");
demoButton = new JButton("导入");
insertButton = new JButton("插入");
moneySortUpButton = new JButton("升序");
moneySortDownButton = new JButton("降序");
sortButton = new JButton("刷新");
deleteButton = new JButton("删除");
changeButton = new JButton("修改");
searchText = new JTextField("输入id或者name查询");
TimeLabel = new JLabel();
searchButton.setBounds(720, 20, 90, 40);
demoButton.setBounds(400, 20, 90, 40);
insertButton.setBounds(305, 700, 90, 40);
changeButton.setBounds(410, 700, 90, 40);
deleteButton.setBounds(515, 700, 90, 40);
moneySortUpButton.setBounds(620, 700, 90, 40);
moneySortDownButton.setBounds(725, 700, 90, 40);
sortButton.setBounds(830, 700, 90, 40);
list.add(searchButton);
list.add(deleteButton);
list.add(demoButton);
list.add(insertButton);
list.add(changeButton);
list.add(moneySortDownButton);
list.add(moneySortUpButton);
list.add(sortButton);
searchButton.addActionListener(this);
demoButton.addActionListener(this);
moneySortUpButton.addActionListener(this);
moneySortDownButton.addActionListener(this);
sortButton.addActionListener(this);
insertButton.addActionListener(this);
deleteButton.addActionListener(this);
changeButton.addActionListener(this);
searchText.setBounds(505, 20, 200, 40);
TimeLabel.setBounds(5, 720, 305, 40);
list.add(searchText);
list.add(TimeLabel);
add(searchButton);
add(demoButton);
add(insertButton);
add(moneySortUpButton);
add(moneySortDownButton);
add(sortButton);
add(deleteButton);
add(changeButton);
add(searchText);
add(TimeLabel);
for (JComponent jComponent : list) {
jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 20));
}
}
//事件监听
@Override
public void actionPerformed(ActionEvent e) {
//给回车键增加按钮监听事件(查询按钮)
//这种方法需要点击一次查询按钮后才会生效
this.getRootPane().setDefaultButton(searchButton);
//查询按钮
if(e.getSource() == searchButton){
tableModel = new TableModel(searchText.getText(), this.dataBase);
bookTable.setModel(tableModel);
}else if (e.getSource() == moneySortUpButton){
tableModel = new TableModel(true, this.dataBase);
bookTable.setModel(tableModel);
}else if (e.getSource() == moneySortDownButton){
tableModel = new TableModel(false, this.dataBase);
bookTable.setModel(tableModel);
}else if (e.getSource() == sortButton){
tableModel = new TableModel(this.dataBase);
bookTable.setModel(tableModel);
}else if(e.getSource() == demoButton){
tableModel = new TableModel(4, this.dataBase);
JOptionPane.showMessageDialog(getContentPane(), "数据为空时才可以导入demo数据!");
}else if(e.getSource() == insertButton){
tableModel = new TableModel(1, this.dataBase);
}else if(e.getSource() == deleteButton){
tableModel = new TableModel(3, this.dataBase);
}else if(e.getSource() == changeButton){
tableModel = new TableModel(2, this.dataBase);
}
}
}
class TableModel
package Work;
import javax.swing.table.AbstractTableModel;
import java.util.*;
//表格模板类
public class TableModel extends AbstractTableModel {
ArrayList<Object> colList = new ArrayList<>();
ArrayList<Book> rowList = new ArrayList<>();
DataBase dataBase;
ArrayList<Book> SQLData;
Object[] tableCol = new Object[]{"ID", "NAME", "AUTHOR", "PRICE", "URL", "YEAR"};
//空参构造,demo数据
public TableModel(DataBase dataBase) {
this.dataBase = dataBase;
SQLData = dataBase.getBookList();
//导入字段
colList.addAll(Arrays.asList(tableCol));
//导入行数据
rowList = new ArrayList<>(SQLData);
}
//查询构造
public TableModel(String text, DataBase dataBase){
this.dataBase = dataBase;
SQLData = dataBase.getBookList();
colList.addAll(Arrays.asList(tableCol));
rowList.clear();
//查询
for (Book objects : SQLData) {
if(text.equals(objects.getId()) || text.equals(objects.getName())){
Book book = new Book(objects.getId(), objects.getName(), objects.getAuthor(), objects.getPrice(), objects.getUrl(), objects.getYear());
rowList.add(book);
return;
}
}
}
//排序
public TableModel(boolean flag, DataBase dataBase){
this.dataBase = dataBase;
SQLData = dataBase.getBookList();
rowList = new ArrayList<>(SQLData);
if(flag){
//升序
rowList.sort(Comparator.comparingInt(o -> (int) o.getPrice()));
}else {
//降序
rowList.sort((o1, o2) -> (int)o2.getPrice() - (int)o1.getPrice());
}
colList.addAll(Arrays.asList(tableCol));
}
//删除,插入和修改
public TableModel(int choice, DataBase dataBase) {
this.dataBase = dataBase;
SQLData = dataBase.getBookList();
switch (choice){
case 1:
try {
new ToolBook(1, dataBase, SQLData);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 2:
try {
new ToolBook(2, dataBase, SQLData);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 3:
try {
new ToolBook(3, dataBase, SQLData);
} catch (Exception e) {
e.printStackTrace();
}
break;
//导入demo数据
case 4:insertDemoData();
break;
default:
break;
}
SQLData = dataBase.getBookList();
}
//导入demo数据
public void insertDemoData(){
if (SQLData.size() == 0){
SQLData = dataBase.insertBook("001", "红楼梦", "曹雪芹", 88.88, "www.aaaaa.com", "1820");
SQLData = dataBase.insertBook("002", "三国演义", "罗贯中", 77, "www.bbbbb.com", "1720");
SQLData = dataBase.insertBook("003", "西游记", "吴承恩", 100, "www.ccccc.com", "1670");
SQLData = dataBase.insertBook("004", "水浒传", "施耐庵", 66.66, "www.ddddd.com", "1784");
}
rowList = SQLData;
}
@Override
public int getRowCount() {
return rowList.size();
}
@Override
public int getColumnCount() {
return colList.size();
}
@Override
public String getColumnName(int columnIndex) {
return (String)colList.get(columnIndex);
}
//禁止直接在方格内修改数据
@Override
public boolean isCellEditable(int row,int col) {
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(columnIndex == 0){
return rowList.get(rowIndex).getId();
}else if(columnIndex == 1){
return rowList.get(rowIndex).getName();
}else if(columnIndex == 2){
return rowList.get(rowIndex).getAuthor();
}
else if(columnIndex == 3){
return rowList.get(rowIndex).getPrice();
}
else if(columnIndex == 4){
return rowList.get(rowIndex).getUrl();
}
return null;
}
public ArrayList<Object> getColList(){
return colList;
}
}
class ToolBook
package Work;
//书本删除,插入和修改类
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class ToolBook extends JFrame {
JButton submitButton, cancelButton;
JLabel idLabel, nameLabel, authorLabel, priceLabel, urlLabel, yearLabel;
JTextField idText, nameText, authorText, priceText, urlText, yearText;
ArrayList<JComponent> list = new ArrayList<>();
DataBase dataBase;
ArrayList<Book> bookList;
//根据choice选择模式
public ToolBook(int choice, DataBase dataBase, ArrayList<Book> bookList) throws Exception {
this.dataBase = dataBase;
this.bookList = bookList;
switch (choice){
case 1:insertFrame();
break;
case 2:changeFrame();
break;
case 3:deleteFrame();
break;
default:
break;
}
}
//插入书本
public void insertFrame(){
//设置窗口的参数
setBounds(500,300,400,400);
//禁用重新调整窗口大小的功能
setResizable(false);
//关闭窗口的右上角
//设置窗口上当前程序的名字
setTitle("图书管理系统--添加图书");
//清除默认的布局管理器
getContentPane().setLayout(null);
//设置窗口显示
setVisible(true);
idLabel = new JLabel(" id:");
nameLabel = new JLabel(" name:");
authorLabel = new JLabel("author:");
priceLabel = new JLabel(" price:");
urlLabel = new JLabel(" url:");
yearLabel = new JLabel(" year:");
list.add(idLabel);
list.add(nameLabel);
list.add(authorLabel);
list.add(priceLabel);
list.add(urlLabel);
list.add(yearLabel);
idLabel.setBounds(15, 0, 90, 40);
nameLabel.setBounds(15, 45, 90, 40);
authorLabel.setBounds(15, 90, 90, 40);
priceLabel.setBounds(15, 135, 90, 40);
urlLabel.setBounds(15, 180, 90, 40);
yearLabel.setBounds(15, 225, 90, 40);
add(idLabel);
add(nameLabel);
add(authorLabel);
add(priceLabel);
add(urlLabel);
add(yearLabel);
/****/
idText = new JTextField();
nameText = new JTextField();
authorText = new JTextField();
priceText = new JTextField();
urlText = new JTextField();
yearText = new JTextField();
list.add(idText);
list.add(nameText);
list.add(authorText);
list.add(priceText);
list.add(urlText);
list.add(yearText);
idText.setBounds(115, 10, 255, 40);
nameText.setBounds(115, 55, 255, 40);
authorText.setBounds(115, 100, 255, 40);
priceText.setBounds(115, 145, 255, 40);
urlText.setBounds(115, 190, 255, 40);
yearText.setBounds(115, 235, 255, 40);
add(idText);
add(nameText);
add(authorText);
add(priceText);
add(urlText);
add(yearText);
submitButton = new JButton("确定");
cancelButton = new JButton("取消");
submitButton.setBounds(120, 290, 100, 40);
cancelButton.setBounds(240, 290, 100, 40);
list.add(submitButton);
list.add(cancelButton);
add(submitButton);
add(cancelButton);
for (JComponent jComponent : list) {
jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));
}
//回车
this.getRootPane().setDefaultButton(submitButton);
submitButton.addActionListener(e -> {
//六项内容不为空
if (!idText.getText().equals("") && !nameText.getText().equals("")
&& !authorText.getText().equals("") && !priceText.getText().equals("")
&& !urlText.getText().equals("") && !yearText.getText().equals("")){
//id不可以重复
for (Book book : bookList) {
if(book.getId().equals(idText.getText())){
JOptionPane.showMessageDialog(getContentPane(), "id重复!");
dispose();
return;
}
}
//插入书本
dataBase.insertBook(idText.getText(), nameText.getText(), authorText.getText(),
Double.parseDouble(priceText.getText()), urlLabel.getText(), yearLabel.getText());
JOptionPane.showMessageDialog(getContentPane(), "添加成功!");
//关闭页面
dispose();
}else {
JOptionPane.showMessageDialog(getContentPane(), "信息不能为空!");
}
});
//取消操作
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(getContentPane(), "已经取消!");
dispose();
}
});
}
//删除书本
public void deleteFrame(){
//设置窗口的参数
setBounds(500,300,400,200);
//禁用重新调整窗口大小的功能
setResizable(false);
//关闭窗口的右上角的叉
//设置窗口上当前程序的名字
setTitle("图书管理系统--删除图书");
//清除默认的布局管理器
getContentPane().setLayout(null);
//设置窗口显示
setVisible(true);
idLabel = new JLabel("id:");
list.add(idLabel);
idLabel.setBounds(35, 10, 90, 40);
add(idLabel);
idText = new JTextField("id为找寻标准");
list.add(idText);
idText.setBounds(75, 10, 285, 40);
add(idText);
submitButton = new JButton("确定");
cancelButton = new JButton("取消");
submitButton.setBounds(80, 90, 100, 40);
cancelButton.setBounds(200, 90, 100, 40);
list.add(submitButton);
list.add(cancelButton);
add(submitButton);
add(cancelButton);
for (JComponent jComponent : list) {
jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));
}
//回车
this.getRootPane().setDefaultButton(submitButton);
submitButton.addActionListener(e -> {
//ID不为空
if (!idText.getText().equals("")){
for (Book book : bookList) {
//找到才删除
if(book.getId().equals(idText.getText())){
dataBase.deleteBook(book.getId());
JOptionPane.showMessageDialog(getContentPane(), "删除成功!");
dispose();
return;
}
}
JOptionPane.showMessageDialog(getContentPane(), "找不到id!");
}else {
JOptionPane.showMessageDialog(getContentPane(), "id不能为空!");
}
});
//取消操作
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(getContentPane(), "已经取消!");
dispose();
}
});
}
//修改书本
public void changeFrame(){
//设置窗口的参数
setBounds(500,300,400,400);
//禁用重新调整窗口大小的功能
setResizable(false);
//关闭窗口的右上角
//设置窗口上当前程序的名字
setTitle("图书管理系统--修改图书");
//清除默认的布局管理器
getContentPane().setLayout(null);
//设置窗口显示
setVisible(true);
idLabel = new JLabel(" id:");
nameLabel = new JLabel(" name:");
authorLabel = new JLabel("author:");
priceLabel = new JLabel(" price:");
urlLabel = new JLabel(" url:");
yearLabel = new JLabel(" year:");
list.add(idLabel);
list.add(nameLabel);
list.add(authorLabel);
list.add(priceLabel);
list.add(urlLabel);
list.add(yearLabel);
idLabel.setBounds(15, 0, 90, 40);
nameLabel.setBounds(15, 45, 90, 40);
authorLabel.setBounds(15, 90, 90, 40);
priceLabel.setBounds(15, 135, 90, 40);
urlLabel.setBounds(15, 180, 90, 40);
yearLabel.setBounds(15, 225, 90, 40);
add(idLabel);
add(nameLabel);
add(authorLabel);
add(priceLabel);
add(urlLabel);
add(yearLabel);
/****/
idText = new JTextField("不可改,id为找寻标准");
nameText = new JTextField("为空则不改(删除此句)");
authorText = new JTextField("为空则不改(删除此句)");
priceText = new JTextField("为空则不改(删除此句)");
urlText = new JTextField("为空则不改(删除此句)");
yearText = new JTextField("为空则不改(删除此句)");
list.add(idText);
list.add(nameText);
list.add(authorText);
list.add(priceText);
list.add(urlText);
list.add(yearText);
idText.setBounds(115, 10, 255, 40);
nameText.setBounds(115, 55, 255, 40);
authorText.setBounds(115, 100, 255, 40);
priceText.setBounds(115, 145, 255, 40);
urlText.setBounds(115, 190, 255, 40);
yearText.setBounds(115, 235, 255, 40);
add(idText);
add(nameText);
add(authorText);
add(priceText);
add(urlText);
add(yearText);
submitButton = new JButton("确定");
cancelButton = new JButton("取消");
submitButton.setBounds(120, 290, 100, 40);
cancelButton.setBounds(240, 290, 100, 40);
list.add(submitButton);
list.add(cancelButton);
add(submitButton);
add(cancelButton);
for (JComponent jComponent : list) {
jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));
}
//回车
this.getRootPane().setDefaultButton(submitButton);
submitButton.addActionListener(e -> {
//ID不为空
if (!idText.getText().equals("")){
for (Book book : bookList) {
//找到ID后修改
if(book.getId().equals(idText.getText())){
//ID不可以改
String name = book.getName();
String author = book.getAuthor();
double price = book.getPrice();
String url = book.getUrl();
String year = book.getYear();
//文本框为空的属性不修改
if(!nameText.getText().equals("")){
name = nameText.getText();
}
if(!authorText.getText().equals("")){
author = authorText.getText();
}
if(!priceText.getText().equals("")){
price = Double.parseDouble(priceText.getText());
}
if(!urlText.getText().equals("")){
url = urlText.getText();
}
if(!yearText.getText().equals("")){
year = yearText.getText();
}
dataBase.changeBook(book.getId(), name, author, price, url, year);
JOptionPane.showMessageDialog(getContentPane(), "修改成功!");
dispose();
return;
}
}
JOptionPane.showMessageDialog(getContentPane(), "找不到id!");
}else {
JOptionPane.showMessageDialog(getContentPane(), "id不能为空!");
}
});
//取消操作
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(getContentPane(), "已经取消!");
dispose();
}
});
}
}
class DataBase
package Work;
import java.sql.*;
import java.util.ArrayList;
//数据库类
public class DataBase {
private String path;//数据库地址及设置
private String id;//数据库账号
private String password;//数据库密码
public Connection con;//连接对象
public Statement state;//执行对象
public DataBase(String path, String id, String password) {
//1.导入jar包,在项目内创建libs目录,将jar包复制到libs目录下
//在idea内右键libs目录选择 Add As Library
//注册数据库驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
this.path = path;
this.id = id;
this.password = password;
dataBase();
/*
String[] strBase = {
"CREATE DATABASE if not exists AtmData DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;",
"use AtmData",
"CREATE TABLE if not exists 'user' (id varchar(20), password varchar(20), money double, vip varchar(5));",
"CREATE TABLE if not exists 'message' (id INT AUTO_INCREMENT, PRIMARY KEY (id), userId varchar(20), type varchar(30), time varchar(30), info varchar(255));"
};
*/
}
//创建连接对象和执行对象
private void dataBase() {
//获取连接对象
try {
this.con = DriverManager.getConnection( this.path, this.id, this.password);
//获取执行对象
this.state = this.con.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取书本集合
public ArrayList<Book> getBookList(){
try {
ResultSet resultSet = this.state.executeQuery("SELECT * FROM Book");
ArrayList<Book> bookList = new ArrayList<>();
while(resultSet.next()){
Book book = new Book(resultSet.getString("id"), resultSet.getString("name"), resultSet.getString("author"), Double.parseDouble(resultSet.getString("price")), resultSet.getString("url"), resultSet.getString("year"));
bookList.add(book);
}
return bookList;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//插入书本
public ArrayList<Book> insertBook(String id, String name, String author, double price, String url, String year){
try {
this.state.execute("INSERT INTO book VALUE ('" + id + "', '" + name + "', '" + author + "', " + price + ", '" + url + "', '" + year + "')");
} catch (SQLException e) {
e.printStackTrace();
}
return getBookList();
}
/*UPDATE book SET id = '005',NAME = 'xxx' WHERE id = '006'*/
//修改书本
public ArrayList<Book> changeBook(String id, String name, String author, double price, String url, String year){
//id不可以改变
try {
this.state.execute("UPDATE book SET NAME = '" + name + "', author = '" + author + "', price = " + price + ", url = '" + url + "', year = '" + year +"' WHERE id = '" + id + "'");
} catch (SQLException e) {
e.printStackTrace();
}
return getBookList();
}
/*DELETE FROM book WHERE id = '005' OR NAME = 'aaa'*/
//删除书本
public ArrayList<Book> deleteBook(String id){
//id不可以改变
try {
this.state.execute("DELETE FROM book WHERE id = '" + id + "'");
} catch (SQLException e) {
e.printStackTrace();
}
return getBookList();
}
//获取用户集合
public ArrayList<User> getUserList(){
try {
ResultSet resultSet = this.state.executeQuery("SELECT * FROM user");
ArrayList<User> userList = new ArrayList<>();
while(resultSet.next()){
User user = new User(resultSet.getString("id"), resultSet.getString("pwd"));
userList.add(user);
}
return userList;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//插入用户
public ArrayList<User> insertUser(String id, String pwd){
try {
this.state.execute("INSERT INTO user VALUE ('" + id + "', '" + pwd + "')");
} catch (SQLException e) {
e.printStackTrace();
}
return getUserList();
}
//修改用户
public ArrayList<User> changeUser(String id, String pwd){
//id不可以改变
try {
this.state.execute("UPDATE user SET pwd = '" + pwd + "' WHERE id = '" + id + "'");
} catch (SQLException e) {
e.printStackTrace();
}
return getUserList();
}
}
class User
package Work;
//用户类
public class User {
private String id;
private String pwd;
public User() {
}
public User(String id, String pwd) {
this.id = id;
this.pwd = pwd;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
class Book
package Work;
import java.util.Objects;
/*****图书类*****/
public class Book {
private String name;//书名
private String id;//图书号
private String author;//作者
private double price;//价格
private String url;//网址
private String year;
//全参构造
public Book(String id, String name, String author, double price, String url, String year) {
this.name = name;
this.id = id;
this.author = author;
if(price >= 0){
this.price = price;
}else{
this.price = 0;
}
this.url = url;
this.year = year;
}
public Book() {
}
//比较判断方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return name.equals(book.name);
}
//未知
@Override
public int hashCode() {
return Objects.hash(name);
}
//toString
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", author='" + author + '\'' +
", price=" + price +
", url='" + url + '\'' +
", year='" + year + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if(price >= 0){
this.price = price;
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getId() {
return id;
}
public void setId(String id) { this.id = id; }
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
相对于非可视化版去掉了message类,这里已经9个文件,table本来也要在封装两个文件的,太烦了,比较javaswing没啥用,主要是满足一下自己。
马上开始学习Javaweb。
需要源程序请自行提取:
链接:https://pan.baidu.com/s/1AcPAq-AGhOKXfycn36RRiA
提取码:mzcu
jar包在