1、JDBC的使用
后面会用到大量jdbc语句来实现数据库的增删改查,可以先简单看看下面这篇文章。
2、对应包和Java文件的层级关系及对应的含义
上面DBUtils为jdbc的封装,详情可以看jdbc的简单使用与封装,还有dp.properties文件也在这篇文章中收到,我后面就不再过多概述。
3、数据库
admin:
book:
category:
4、相关代码
1)、bookmanager包
Ⅰ、main函数
BookManagerApplication
package com.hk.sky.bookmanager; import com.hk.sky.bookmanager.bean.Admin; import com.hk.sky.bookmanager.controller.LoginController; import com.hk.sky.bookmanager.dao.AdminDao; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; import java.io.IOException; public class BookManagerApplication extends Application { AdminDao adminDao=new AdminDao(); //获取上一次用户登录的信息 Admin admin=adminDao.getLast(); @Override public void start(Stage stage) throws IOException { //登录页面的资源文件为login/login.fxml FXMLLoader fxmlLoader = new FXMLLoader(BookManagerApplication.class.getResource("login/login.fxml")); //设置登录窗口的长和宽 Scene scene = new Scene(fxmlLoader.load(), 290, 240); stage.setTitle("管理员登录"); stage.setScene(scene); LoginController loginController=fxmlLoader.getController(); //如果admin不是为null,则说明上一次有用户登录,则直接在登录页面显示账号和密码 if (admin!=null) loginController.set(admin.getAccount(),admin.getPassword()); stage.show(); } //启动 public static void main(String[] args) { launch(); } }
Ⅱ、utils包
DBUtils
package com.hk.sky.bookmanager.utils; import java.io.IOException; import java.sql.*; import java.util.Properties; /** * 封装数据连接,关闭的工具类 */ public class DBUtils { private static String url; private static String username; private static String password; // 读取配置文件 static { Properties prop = new Properties(); try { // DBUtils.class.getClassLoader().getResourceAsStream()方法可以从类路径中读取资源文件 prop.load(DBUtils.class.getClassLoader().getResourceAsStream("db.properties")); // 通过key获取value url = prop.getProperty("jdbc.url"); username = prop.getProperty("jdbc.username"); password = prop.getProperty("jdbc.password"); } catch (IOException e) { throw new RuntimeException(e); } } // 将创建连接的方法封装成静态方法,方便调用 // 如何将url、username、password放到配置文件当中,然后读取出来 public static Connection getConnection() { // 创建连接的时候,有会异常:SQLException,不建议抛出,建立捕获 Connection conn = null; try { conn = DriverManager.getConnection( url, username, password ); } catch (SQLException e) { e.printStackTrace(); } return conn; } // 将关闭连接的方法封装成静态方法,方便调用 public static void close(ResultSet rs, PreparedStatement pStmt, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pStmt != null) { try { pStmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
Ⅲ、bean包
Admin
package com.hk.sky.bookmanager.bean; public class Admin { //账号 private String account; //密码 private String password; //上一次登录 private int last; public String getAccount() { return account; } public String getPassword() { return password; } public void setAccount(String account) { this.account = account; } public void setPassword(String password) { this.password = password; } public int getLast() { return last; } public void setLast(int last) { this.last = last; } @Override public String toString() { return "Admin{" + "account='" + account + '\'' + ", password='" + password + '\'' + ", last=" + last + '}'; } }
book
package com.hk.sky.bookmanager.bean; public class Book { private int id; private String bookName; private String author; private int price; private int stock; private String publisher; private String detail; private int typeId; public void setDetail(String detail) { this.detail = detail; } public String getDetail() { return detail; } public int getId() { return id; } public String getBookName() { return bookName; } public String getAuthor() { return author; } public int getPrice() { return price; } public int getStock() { return stock; } public String getPublisher() { return publisher; } public void setId(int id) { this.id = id; } public void setBookName(String bookName) { this.bookName = bookName; } public void setAuthor(String author) { this.author = author; } public void setPrice(int price) { this.price = price; } public void setStock(int stock) { this.stock = stock; } public void setPublisher(String publisher) { this.publisher = publisher; } public void setTypeId(int typeId) { this.typeId = typeId; } public int getTypeId() { return typeId; } public Book(){} public Book(String name, String author, String publisher, int price, String detail, int stock, int typeId) { this.bookName = name; this.author = author; this.publisher = publisher; this.price = price; this.detail = detail; this.stock = stock; this.typeId = typeId; } }
Category
package com.hk.sky.bookmanager.bean; public class Category { private int id; private String typeName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } @Override public String toString() { return typeName; } }
Ⅳ、controller包
AddController
package com.hk.sky.bookmanager.controller; import com.hk.sky.bookmanager.bean.Book; import com.hk.sky.bookmanager.bean.Category; import com.hk.sky.bookmanager.dao.BookDao; import com.hk.sky.bookmanager.dao.CategoryDao; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.stage.Stage; import java.net.URL; import java.sql.SQLException; import java.util.*; public class AddController implements Initializable { @FXML public Button add; @FXML public Button edit; @FXML private ComboBox<Category> categoryComboBox; private ObservableList<Category> observableList = FXCollections.observableArrayList(); private CategoryDao categoryDao = new CategoryDao(); private BookDao bookDao = new BookDao(); @FXML private TextField bookName; @FXML private TextField bookAuthor; @FXML private TextField bookPublisher; @FXML private TextField bookPrice; @FXML private TextField detail; @FXML private TextField bookStock; public Book book; public void setBook(Book book) { this.book = book; } //B用来判断是添加书籍还是编辑书籍 public boolean B; public void setB(boolean i){ this.B=i; } @Override public void initialize(URL url, ResourceBundle resourceBundle) { Platform.runLater(() -> { // 页面第一次加载的时候,就显示下拉列表 observableList.clear(); List<Category> categories = categoryDao.getAllCategories(); observableList.addAll(categories); categoryComboBox.setItems(observableList); //添加书籍 修改书籍 if (B){ add.setVisible(true); add.setText("添加"); edit.setVisible(false); edit.setText(""); categoryComboBox.setValue(categories.get(0)); }else { bookName.setText(book.getBookName()); bookAuthor.setText(book.getAuthor()); bookPublisher.setText(book.getPublisher()); bookPrice.setText(String.valueOf(book.getPrice())); detail.setText(book.getDetail()); bookStock.setText(String.valueOf(book.getStock())); categoryComboBox.setValue(categories.get(book.getTypeId())); edit.setVisible(true); edit.setText("修改"); add.setDisable(false); add.setText(""); } }); } //给添加按钮设置点击事件 public void addBook() throws SQLException { // 用户点击添加按钮时,获取所有的数据,并插入到数据库当中 String name = bookName.getText(); String author = bookAuthor.getText(); String publisher = bookPublisher.getText(); String detail1 = detail.getText(); // 将格式进行转换 // 表单验证,判断用户是否输入内容 if (name.equals("") || author.equals("") || publisher.equals("") || detail1.equals("") || bookPrice.getText().equals("") || bookStock.getText().equals("")) { Alert error = new Alert(Alert.AlertType.ERROR, "输入错误"); Button err = new Button(); error.setTitle("您的书籍信息输入错误!"); error.setHeaderText("请正确填写所要添加书籍的信息!"); err.setOnAction((ActionEvent e) -> { error.showAndWait(); }); Optional<ButtonType> result = error.showAndWait(); } else if (!bookPrice.getText().matches("[1-9]+[0-9]*")||!bookStock.getText().matches("[1-9]+[0-9]*")){ Alert error = new Alert(Alert.AlertType.ERROR, "输入错误"); Button err = new Button(); error.setTitle("您的书籍信息输入错误!"); error.setHeaderText("库存和价格必须为整数!"); err.setOnAction((ActionEvent e) -> { error.showAndWait(); }); Optional<ButtonType> result = error.showAndWait(); }else{ // 思路:将上面获取到的数据封装成book,然后插入到数据库当中 // 但是仔细思考,我们会碰到一个难点:如何获取ComboBox的选项?也就是说如何知道用户选的是哪一个类型的书籍? Category selectedCategory = categoryComboBox.getValue(); int price = Integer.parseInt(bookPrice.getText()); int stock = Integer.parseInt(bookStock.getText()); // 将所有的数据封装成书籍 Book book = new Book(name, author, publisher, price, detail1, stock, selectedCategory.getId()); // 调用BookDao中的方法将数据插入到数据库当中 Alert information = new Alert(Alert.AlertType.INFORMATION, "恭喜您书籍添加成功"); Button err = new Button(); information.setTitle("添加成功!"); information.setHeaderText("林氏图书馆又收录了一本新书,感谢!"); err.setOnAction((ActionEvent e) -> { information.showAndWait(); }); Optional<ButtonType> result = information.showAndWait(); // 插入成功之后,首先当前属性应该关闭 if (bookDao.insertBook(book)){ ((Stage) bookName.getScene().getWindow()).close(); } } } //给编辑按钮设置点击事件 public void editBook(ActionEvent actionEvent) throws SQLException{ // 用户点击添加按钮时 ,获取所有的数据,并插入到数据库当中 String name = bookName.getText(); String author = bookAuthor.getText(); String publisher = bookPublisher.getText(); String detail1 = detail.getText(); // 将格式进行转换 // 表单验证,判断用户是否输入内容 if (name.equals("")||author.equals("")||publisher.equals("")||detail1.equals("")|| bookPrice.getText().equals("")||bookStock.getText().equals("")){ Alert error=new Alert(Alert.AlertType.ERROR,"输入错误"); Button err=new Button(); error.setTitle("您的书籍信息输入错误!"); error.setHeaderText("请正确填写所要修改书籍的信息!"); err.setOnAction((ActionEvent e)->{ error.showAndWait(); }); Optional<ButtonType> result = error.showAndWait(); }else if (!bookPrice.getText().matches("[1-9]+[0-9]*")||!bookStock.getText().matches("[1-9]+[0-9]*")){ Alert error = new Alert(Alert.AlertType.ERROR, "输入错误"); Button err = new Button(); error.setTitle("您的书籍信息输入错误!"); error.setHeaderText("库存和价格必须为整数!"); err.setOnAction((ActionEvent e) -> { error.showAndWait(); }); Optional<ButtonType> result = error.showAndWait(); }else { int price = Integer.parseInt(bookPrice.getText()); int stock = Integer.parseInt(bookStock.getText()); // 思路:将上面获取到的数据封装成book,然后插入到数据库当中 // 但是仔细思考,我们会碰到一个难点:如何获取ComboBox的选项?也就是说如何知道用户选的是哪一个类型的书籍? Category selectedCategory = categoryComboBox.getValue(); // 将所有的数据封装成书籍 Book book1 = new Book(name, author, publisher, price, detail1, stock, selectedCategory.getId()); book1.setId(book.getId()); // 调用BookDao中的方法将数据插入到数据库当中 Alert information=new Alert(Alert.AlertType.INFORMATION,"恭喜您书籍信息修改成功"); Button err=new Button(); information.setTitle("修改成功!"); information.setHeaderText("谢谢您为林氏图书馆添砖加瓦,感谢!"); err.setOnAction((ActionEvent e)->{ information.showAndWait(); }); Optional<ButtonType> result = information.showAndWait(); boolean success = bookDao.updateBook(book1); // 插入成功之后,首先当前属性应该关闭 if (success) { ((Stage)bookName.getScene().getWindow()).close(); } } } }
EnrollController
package com.hk.sky.bookmanager.controller; import com.hk.sky.bookmanager.bean.Admin; import com.hk.sky.bookmanager.dao.AdminDao; import com.hk.sky.bookmanager.utils.DBUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.text.Text; import javafx.stage.Stage; import java.sql.Connection; import java.sql.SQLException; import java.util.Objects; import java.util.Optional; public class EnrollController { @FXML public TextField username1; @FXML public PasswordField password1; @FXML public Text errorMsg;//提示错误信息 @FXML private Button alert; @FXML private Button enroll; @FXML public Text title; AdminDao adminDao=new AdminDao(); //给注册按钮设置点击事件 public void enrollBtn() { String account=username1.getText(); String pw=password1.getText(); if (Objects.equals(account, "")){ errorMsg.setText("请填写用户名"); }else if (Objects.equals(pw, "")){ errorMsg.setText("请填写密码"); }else { boolean b=adminDao.enroll(account,pw); if(!b){ errorMsg.setText("用户名已使用,请更改用户名!"); }else { Alert information=new Alert(Alert.AlertType.INFORMATION,"恭喜"+account+"用户注册成功"); Button err=new Button(); information.setTitle("注册成功!"); information.setHeaderText("林氏图书馆欢迎您的到来!"); err.setOnAction((ActionEvent e)->{ information.showAndWait(); }); Optional<ButtonType> result = information.showAndWait(); // 关闭当前Stage,问题:如何获取当前的stage? Stage currentWindow = (Stage)username1.getScene().getWindow(); currentWindow.close(); } } } //区分是注册还是修改密码,修改密码的话账号无法更改,输入框为不可选择,注册按钮消失,修改按钮显示 public void qf(boolean b){ if (b){ enroll.setVisible(false); alert.setVisible(true); username1.setDisable(true); } } //s用来保存原密码,修改密码无法更改为原密码 public String s; public void setS(String ss){ s=ss; } //给修改密码设置点击事件 public void alertBtn() throws SQLException { if (password1.getText().equals("")){ errorMsg.setText("密码不能为空"); }else if(password1.getText().equals(s)){ errorMsg.setText("不能与最近使用密码相同"); }else { Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "你是否真的要修改该密码?"); alert.setTitle("修改密码"); alert.setHeaderText("确认修改?"); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent()){ adminDao.alertPassword(username1.getText(),password1.getText()); Alert information = new Alert(Alert.AlertType.INFORMATION, "恭喜您修改密码成功!"); Button err = new Button(); information.setTitle("修改密码"); information.setHeaderText("修改密码成功!"); err.setOnAction((ActionEvent e) -> { information.showAndWait(); }); Optional<ButtonType> rs = information.showAndWait(); } } } }
HouTaiController
package com.hk.sky.bookmanager.controller; import com.hk.sky.bookmanager.BookManagerApplication; import com.hk.sky.bookmanager.bean.Admin; import com.hk.sky.bookmanager.bean.Book; import com.hk.sky.bookmanager.dao.AdminDao; import com.hk.sky.bookmanager.dao.BookDao; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.text.Text; import javafx.stage.Stage; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.ResourceBundle; public class HouTaiController implements Initializable { /*搜索框*/ public TextField search; /*下拉框*/ public ComboBox categorySelect; // 不能直接从这里查询用户信息,因为在当前这个类当中,我不知道是谁登录了 // 通过上一个类传递到当前类当中,我们需要在当前类中定义要传递的数据,然后通过set方法设置该属性的值 private Admin admin; public String bookName; public String bookAuthor; public String Publish; //表示查询到的行 public int sumPage; //n表示页数 public int n; public void setAdmin(Admin admin) { this.admin = admin; } public void setSumPage(int i){ this.sumPage=i; double j=i/9.0; n=(int) Math.ceil(j); } public void setBookName(String s){ bookName=s; } @FXML private Text welcomeMsg; @FXML private Text searchCount; @FXML private Text searchPage; @FXML//返回按钮 private Button fh; //给表添加数据 @FXML private TableView<Book> bookTable; // 准备表格中的数据 private ObservableList<Book> data = FXCollections.observableArrayList(); // 准备dao类,它负责到数据库中查询 private BookDao bookDao = new BookDao(); private AdminDao adminDao=new AdminDao(); //添加按钮操作 // 编辑按钮 private TableColumn<Book, Integer> editColumn = new TableColumn<>("编辑"); // 删除按钮 private TableColumn<Book, Integer> delColumn = new TableColumn<>("删除"); // 详情按钮 private TableColumn<Book, Integer> detailColumn = new TableColumn<>("详情"); // 上一个页面中将admin传递过来,我们需要在当前窗口中来获取传递过来的数据,然后将值设置给页面中的元素显示 // 将当前类实现Initializable接口,然后在initialize(初始化)方法中获取设置的值,然后设置给页面中的元素 @Override public void initialize(URL url, ResourceBundle resourceBundle) { // 通过UI线程获取值,并设置值 Platform.runLater(() -> { welcomeMsg.setText("欢迎" + admin.getAccount() + "管理员登录!"); searchCount.setText("共"+sumPage+"条记录"); categorySelect.getItems().addAll( "书名", "出版社", "作者" ); categorySelect.setValue("书名"); // 查询数据库,设置ObservableList,并添加至tableView当中 List<Book> books = bookDao.set(search.getText(),0); data.addAll(books); bookTable.setItems(data); //1、添加编辑按钮 editColumn.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getId())); editColumn.setCellFactory(param -> new TableCell<>(){ final Button editBtn = new Button("编辑"); @Override protected void updateItem(Integer item, boolean empty) { super.updateItem(item, empty); if (item == null) { setGraphic(null); return; } setGraphic(editBtn); // 添加点击事件 editBtn.setOnMouseClicked(event ->{ try { Stage newStage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader(BookManagerApplication.class.getResource("book/add.fxml")); Scene scene = new Scene(fxmlLoader.load(), 280, 400); newStage.setTitle("编辑书籍"); newStage.setScene(scene); AddController addController=fxmlLoader.getController(); addController.setB(false); addController.setBook(bookDao.getbookById(item)); newStage.show(); // 我们需要监听添加页面关闭后,刷新tableview // CloseRequest()只有在用户点击右上角的叉时才会触发 newStage.setOnHiding(evt->{ refreshTableView(i); }); } catch (IOException e) { throw new RuntimeException(e); } }); } }); //将列添加至表中 bookTable.getColumns().add(editColumn); //2、添加删除按钮 delColumn.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getId())); delColumn.setCellFactory(param -> new TableCell<>(){ // 创建删除按钮 final Button editBtn = new Button("删除"); @Override protected void updateItem(Integer item, boolean empty) { super.updateItem(item, empty); if (item == null) { setGraphic(null); return; } setGraphic(editBtn); // 添加点击事件 editBtn.setOnMouseClicked(event -> { // 添加一个对话框,判断用户是否需要真的删除 Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "你是否需要真的删除这本吗?"); alert.setTitle("警告"); alert.setHeaderText("确认删除?"); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent() && result.get() == ButtonType.OK) { // 实现删除功能 bookDao.deleteBookById(item); // 刷新页面 refreshTableView(i); } }); } }); //将列添加至表中 bookTable.getColumns().add(delColumn); // 3、添加详情按钮 detailColumn.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getId())); detailColumn.setCellFactory(param -> new TableCell<>(){ // 创建详情按钮 final Button editBtn = new Button("详情"); @Override protected void updateItem (Integer item,boolean empty){ super.updateItem(item, empty); if (item == null) { setGraphic(null); return; } setGraphic(editBtn); // 添加点击事件 editBtn.setOnMouseClicked(event -> { try { Stage newStage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader(BookManagerApplication.class.getResource("book/show.fxml")); Scene scene = new Scene(fxmlLoader.load(), 280, 270); newStage.setTitle("书籍详情"); newStage.setScene(scene); // 将当前书籍id传递到下一个页面当中 ShowController showController = fxmlLoader.getController(); showController.setBook(bookDao.getbookById(item)); // 显示要打开的Stage,stage.show() newStage.show(); } catch (IOException e) { throw new RuntimeException(e); } }); //将列添加至表中 } }); bookTable.getColumns().add(detailColumn); }); } public void refreshTableView(int i){ // 在往集合中添加数据之前,先清空集合 data.clear(); List<Book> books = null; // 查询数据库,设置ObservableList,并添加至tableView当中 if(categorySelect.getValue().equals("作者")&&bookAuthor!=null) { setSumPage(bookDao.likeSumCountByAuthor(search.getText())); if (i==n) i--; books= bookDao.setByAuthor(bookAuthor, i); searchCount.setText("共"+bookDao.likeSumCountByAuthor(search.getText())+"条记录"); }else if (categorySelect.getValue().equals("出版社")&&Publish!=null){ setSumPage(bookDao.likeSumCountByPublish(search.getText())); if (i==n) i--; books= bookDao.setByPublish(Publish, i); searchCount.setText("共"+bookDao.likeSumCountByPublish(search.getText())+"条记录"); }else { setSumPage(bookDao.likeSumCount(search.getText())); if (i==n) i--; books= bookDao.set(bookName, i); searchCount.setText("共"+bookDao.likeSumCount(search.getText())+"条记录"); } data.addAll(books); bookTable.setItems(data); int z=i+1; searchPage.setText("第"+z+"页"); } int i=0; //首页按钮 public void start(){ if (i!=0){ data.clear(); List<Book> books=null; // 查询数据库,设置ObservableList,并添加至tableView当中 if (categorySelect.getValue().equals("出版社")&&Publish!=null){ books=bookDao.setByPublish(Publish,0); }else if (categorySelect.getValue().equals("作者")&&bookAuthor!=null){ books=bookDao.setByAuthor(bookAuthor,0); }else { books= bookDao.set(bookName,0); } data.addAll(books); bookTable.setItems(data); i=0; searchPage.setText("第"+1+"页"); } } //尾页按钮 public void end(){ if (i!=n-1){ data.clear(); List<Book> books=null; // 查询数据库,设置ObservableList,并添加至tableView当中 // 查询数据库,设置ObservableList,并添加至tableView当中 if (categorySelect.getValue().equals("出版社")&&Publish!=null){ books=bookDao.setByPublish(Publish,n-1); }else if (categorySelect.getValue().equals("作者")&&bookAuthor!=null){ books=bookDao.setByAuthor(bookAuthor,n-1); }else { books= bookDao.set(bookName,n-1); } data.addAll(books); bookTable.setItems(data); i=n-1; searchPage.setText("第"+n+"页"); } } //上一页按钮 public void up(){ if (i>0&&i<=n-1){ data.clear(); // 查询数据库,设置ObservableList,并添加至tableView当中 List<Book> books=null; // 查询数据库,设置ObservableList,并添加至tableView当中 if (categorySelect.getValue().equals("出版社")&&Publish!=null){ books=bookDao.setByPublish(Publish,--i); }else if (categorySelect.getValue().equals("作者")&&bookAuthor!=null){ books=bookDao.setByAuthor(bookAuthor,--i); }else { books= bookDao.set(bookName,--i); } data.addAll(books); bookTable.setItems(data); int z=i+1; searchPage.setText("第"+z+"页"); } } //下一页按钮 public void next(){ if (i<n-1&&i>=0){ data.clear(); // 查询数据库,设置ObservableList,并添加至tableView当中 List<Book> books=null; // 查询数据库,设置ObservableList,并添加至tableView当中 if (categorySelect.getValue().equals("出版社")&&Publish!=null){ books=bookDao.setByPublish(Publish,++i); }else if (categorySelect.getValue().equals("作者")&&bookAuthor!=null){ books=bookDao.setByAuthor(bookAuthor,++i); }else { books= bookDao.set(bookName,++i); } data.addAll(books); bookTable.setItems(data); int z=i+1; searchPage.setText("第"+z+"页"); } } //搜索按钮 public void searchBtn() throws IOException { if (categorySelect.getValue().equals("书名")){ if (!Objects.equals(search.getText(), "")){ if (bookDao.likeSumCount(search.getText())==0){ Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "抱歉,为查找到有关该图书!"); alert.setTitle("查找错误"); alert.setHeaderText("请重新填写所要查找书籍的名称!"); Optional<ButtonType> result = alert.showAndWait(); }else { fh.setVisible(true); bookName=search.getText(); // 在往集合中添加数据之前,先清空集合 data.clear(); // 查询数据库,设置ObservableList,并添加至tableView当中 List<Book> books = bookDao.set(bookName,0); data.addAll(books); bookTable.setItems(data); setSumPage(bookDao.likeSumCount(bookName)); searchCount.setText("共"+bookDao.likeSumCount(search.getText())+"条记录"); i=0; searchPage.setText("第"+1+"页"); } }else { Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "错误,搜索框中未输入查询数据!"); alert.setTitle("输入错误"); alert.setHeaderText("请填写所要查找书籍的名称,书籍名不能为空!"); Optional<ButtonType> result = alert.showAndWait(); } }else if (categorySelect.getValue().equals("作者")){ if (!Objects.equals(search.getText(), "")){ if (bookDao.likeSumCountByAuthor(search.getText())==0){ Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "抱歉,未查找到有关该图书!"); alert.setTitle("查找错误"); alert.setHeaderText("请重新填写所要查找书籍的作者!"); Optional<ButtonType> result = alert.showAndWait(); }else { fh.setVisible(true); bookAuthor=search.getText(); // 在往集合中添加数据之前,先清空集合 data.clear(); // 查询数据库,设置ObservableList,并添加至tableView当中 List<Book> books = bookDao.setByAuthor(bookAuthor,0); data.addAll(books); bookTable.setItems(data); setSumPage(bookDao.likeSumCountByAuthor(bookAuthor)); searchCount.setText("共"+bookDao.likeSumCountByAuthor(bookAuthor)+"条记录"); i=0; searchPage.setText("第"+1+"页"); } }else { Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "错误,搜索框中未输入查询数据!"); alert.setTitle("输入错误"); alert.setHeaderText("请填写所要查找书籍的作者,作者名不能为空!"); Optional<ButtonType> result = alert.showAndWait(); } }else { if (!Objects.equals(search.getText(), "")){ if (bookDao.likeSumCountByPublish(search.getText())==0){ Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "抱歉,未查找到有关该图书!"); alert.setTitle("查找错误"); alert.setHeaderText("请重新填写所要查找书籍的出版社!"); Optional<ButtonType> result = alert.showAndWait(); }else { fh.setVisible(true); Publish=search.getText(); // 在往集合中添加数据之前,先清空集合 data.clear(); // 查询数据库,设置ObservableList,并添加至tableView当中 List<Book> books = bookDao.setByPublish(Publish,0); data.addAll(books); bookTable.setItems(data); setSumPage(bookDao.likeSumCountByPublish(Publish)); searchCount.setText("共"+bookDao.likeSumCountByPublish(Publish)+"条记录"); i=0; searchPage.setText("第"+1+"页"); } }else { Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "错误,搜索框中未输入查询数据!"); alert.setTitle("输入错误"); alert.setHeaderText("请填写所要查找书籍的出版社,出版社名不能为空!"); Optional<ButtonType> result = alert.showAndWait(); } } } //删除按钮 public void deleteBtn() { Book book1=null; String bookName=search.getText(); book1=bookDao.getBookByBookName(bookName); if (book1!=null){ // 添加一个对话框,判断用户是否需要真的删除 Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "你是否需要真的删除这本书吗?"); alert.setTitle("警告"); alert.setHeaderText("确认删除?"); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent() && result.get() == ButtonType.OK) { // 实现删除功能 bookDao.deleteBookByBookName(bookName); // 刷新页面 refreshTableView(i); } }else { // 添加一个对话框,告诉用户没有这本书 Alert error=new Alert(Alert.AlertType.ERROR,"删除错误,该图书馆未收录此书!"); Button err=new Button(); error.setTitle("删除错误!"); error.setHeaderText("请重新填写要删除的书籍!"); err.setOnAction((ActionEvent e)->{ error.showAndWait(); }); Optional<ButtonType> result = error.showAndWait(); } } //添加按钮 public void addBtn() { try { Stage newStage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader(BookManagerApplication.class.getResource("book/add.fxml")); Scene scene = new Scene(fxmlLoader.load(), 280, 400); newStage.setTitle("添加书籍"); newStage.setScene(scene); AddController addController=fxmlLoader.getController(); addController.setB(true); newStage.show(); // 我们需要监听添加页面关闭后,刷新tableview // CloseRequest()只有在用户点击右上角的叉时才会触发 newStage.setOnHiding(event -> { refreshTableView(i); }); } catch (IOException e) { throw new RuntimeException(e); } } //返回按钮 public void back(ActionEvent actionEvent) { categorySelect.setValue("书名"); search.setText(""); bookName=search.getText(); // 在往集合中添加数据之前,先清空集合 data.clear(); // 查询数据库,设置ObservableList,并添加至tableView当中 List<Book> books = bookDao.set(bookName,0); data.addAll(books); bookTable.setItems(data); setSumPage(bookDao.likeSumCount(bookName)); searchCount.setText("共"+bookDao.likeSumCount(search.getText())+"条记录"); i=0; searchPage.setText("第"+1+"页"); fh.setVisible(false); } //注销按钮 public void zx(ActionEvent actionEvent) throws IOException { Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "你是否真的要注销该账号?"); alert.setTitle("警告"); alert.setHeaderText("确认注销?"); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent() && result.get() == ButtonType.OK) { adminDao.delete(admin.getAccount()); //提醒用户该账号已注销,请重新登录 Alert information = new Alert(Alert.AlertType.INFORMATION, "该账号已注销!"); Button err = new Button(); information.setTitle("登录失败!"); information.setHeaderText("该账号已注销,请重新登录"); err.setOnAction((ActionEvent e) -> { information.showAndWait(); }); Optional<ButtonType> result1 = information.showAndWait(); //关闭 后台 页面 Stage currentWindow = (Stage)search.getScene().getWindow(); currentWindow.close(); //重新显示登录页面 Stage stage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader(BookManagerApplication.class.getResource("login/login.fxml")); Scene scene = new Scene(fxmlLoader.load(), 290, 240); stage.setTitle("用户登录"); stage.setScene(scene); stage.show(); } } //修改密码 public void xgmm(ActionEvent actionEvent) throws IOException { Stage stage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader(BookManagerApplication.class.getResource("login/enroll.fxml")); Scene scene = new Scene(fxmlLoader.load(), 290, 251); stage.setTitle("修改密码"); stage.setScene(scene); EnrollController enrollController=fxmlLoader.getController(); enrollController.username1.setText(admin.getAccount()); enrollController.password1.setText(admin.getPassword()); String s=admin.getPassword(); enrollController.title.setText("修改密码"); enrollController.setS(admin.getPassword()); enrollController.qf(true); stage.show(); //添加监听事件,检查密码是否更换 stage.setOnHiding(evt -> { try { if (adminDao.checkPassword(admin.getAccount(),s)){ Alert information = new Alert(Alert.AlertType.INFORMATION, "该账号已注销!"); Button err = new Button(); information.setTitle("登录失败!"); information.setHeaderText("该账号已注销,请重新登录"); err.setOnAction((ActionEvent e) -> { information.showAndWait(); }); Optional<ButtonType> result1 = information.showAndWait(); //关闭 后台 页面 Stage currentWindow = (Stage)search.getScene().getWindow(); currentWindow.close(); //重新显示登录页面 Stage stage1 = new Stage(); FXMLLoader fxmlLoader1 = new FXMLLoader(BookManagerApplication.class.getResource("login/login.fxml")); Scene scene1 = new Scene(fxmlLoader1.load(), 290, 240); stage1.setTitle("用户登录"); stage1.setScene(scene1); LoginController loginController=fxmlLoader1.getController(); loginController.username.setText(admin.getAccount()); stage1.show(); adminDao.reset(); } } catch (IOException e) { throw new RuntimeException(e); } }); } }
LoginController
package com.hk.sky.bookmanager.controller; import com.hk.sky.bookmanager.BookManagerApplication; import com.hk.sky.bookmanager.bean.Admin; import com.hk.sky.bookmanager.dao.AdminDao; import com.hk.sky.bookmanager.dao.BookDao; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.text.Text; import javafx.stage.Stage; import java.io.IOException; public class LoginController { @FXML public TextField username; @FXML private PasswordField password; @FXML private Text errorMsg; //设置上一次登录账号的账号密码 public void set(String un,String pw){ if (un!=null&&pw!=null){ username.setText(un); password.setText(pw); } } @FXML //登录按钮 检查是否有该账号以及账号密码的正确性 public void checkLogin() throws IOException { // 获取输入框中的内容 String uname = username.getText(); String pwd = password.getText(); // 判断用户名与密码 AdminDao adminDao = new AdminDao(); Admin admin = adminDao.checkLogin(uname, pwd); if (admin == null) { errorMsg.setText("用户名或者密码错误"); } else { // 跳转到后面页面 // 创建要打开的Stage,问题:stage如何创建? Stage newStage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader(BookManagerApplication.class.getResource("book/houtai.fxml")); Scene scene = new Scene(fxmlLoader.load(), 700, 430); newStage.setTitle("后台页面"); newStage.setScene(scene); // 关闭当前Stage,问题:如何获取当前的stage? Stage currentWindow = (Stage) username.getScene().getWindow(); currentWindow.close(); //消除上次用户登录的信息 adminDao.reset(); //保存这次用户登录的信息 adminDao.setLast(username.getText()); // 将当前用户的信息传递到下一个页面当中 HouTaiController houTaiController = fxmlLoader.getController(); BookDao bookdao=new BookDao(); houTaiController.setSumPage(bookdao.sumPage()); houTaiController.setAdmin(admin); houTaiController.setBookName(""); // 显示要打开的Stage,stage.show() newStage.show(); } } //注册按钮 public void enrollLogin() throws IOException{ Stage stage = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader(BookManagerApplication.class.getResource("login/enroll.fxml")); Scene scene = new Scene(fxmlLoader.load(), 290, 251); stage.setTitle("用户注册"); stage.setScene(scene); stage.show(); } }
ShowController
package com.hk.sky.bookmanager.controller; import com.hk.sky.bookmanager.bean.Book; import com.hk.sky.bookmanager.dao.BookDao; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.text.Text; import java.net.URL; import java.util.ResourceBundle; public class ShowController implements Initializable { @FXML public Text bookId; Book book=null; public void setBook(Book book1){ this.book=book1; } private BookDao bookDao = new BookDao(); @FXML private Text bookName; @FXML private Text bookAuthor; @FXML private Text bookPublish; @FXML private Text bookPrice; @FXML private Text bookStock; @FXML private Text bookDetail; //书籍详情页面显示 @Override public void initialize(URL url, ResourceBundle resourceBundle) { Platform.runLater(() -> { bookId.setText(String.valueOf(book.getId())); bookName.setText(book.getBookName()); bookAuthor.setText(book.getAuthor()); bookPublish.setText(book.getPublisher()); bookPrice.setText(String.valueOf(book.getPrice())); bookStock.setText(String.valueOf(book.getStock())); bookDetail.setText(book.getDetail()); }); } }
module-info
module com.example.bookmange { requires javafx.controls; requires javafx.fxml; requires javafx.web; requires org.controlsfx.controls; requires validatorfx; requires org.kordamp.ikonli.javafx; requires org.kordamp.bootstrapfx.core; requires eu.hansolo.tilesfx; requires java.sql; opens com.hk.sky.bookmanager to javafx.fxml; exports com.hk.sky.bookmanager; exports com.hk.sky.bookmanager.controller; opens com.hk.sky.bookmanager.controller to javafx.fxml; opens com.hk.sky.bookmanager.bean to javafx.base; }