如何给JavaFX表格每行添加购买按钮并将书籍加入购物车区域
解决JavaFX表格Buy按钮绑定Controller事件的问题
1. 调整CustomerView,添加Buy事件回调接口
在CustomerView中修改硬编码的打印逻辑,改为通过回调将点击事件传递给Controller处理:
- 添加成员变量存储回调逻辑:
private Consumer<Book> buyBookHandler;
- 添加设置回调的方法:
public void setBuyBookHandler(Consumer<Book> handler) { this.buyBookHandler = handler; }
- 修改
initializeTableView中Buy按钮的点击事件,触发回调:
buyButton.setOnAction(event -> { Book book = getTableView().getItems().get(getIndex()); if (buyBookHandler != null) { buyBookHandler.accept(book); } });
- 修复总价显示的拼接问题:
public void setPriceTotal(int price){ totalPriceLabel.setText("Total price: " + price); }
2. 在CustomerController中实现购物车逻辑
移除原有的BuyBook内部类,直接通过回调绑定购物车添加逻辑:
- 添加总价成员变量:
private int totalPrice = 0;
- 在构造函数中绑定Buy按钮的处理逻辑:
public CustomerController(CustomerView customerView, BookService bookService) { this.customerView = customerView; this.bookService = bookService; // 绑定Buy按钮的购物车逻辑 this.customerView.setBuyBookHandler(book -> { int stock = book.getStock(); if(stock > 0){ book.setStock(stock - 1); // 向购物车区域添加书籍信息 customerView.setCartArea(book.getTitle() + " - $" + book.getPrice() + "\n"); booksInCart.add(book); // 更新总价 totalPrice += book.getPrice(); customerView.setPriceTotal(totalPrice); } else { customerView.setCartArea("已售罄: " + book.getTitle() + "\n"); } }); this.customerView.showAllBooks(new ViewAllBooks()); }
- 删除不再使用的
BuyBook内部类。
3. 说明
- 调整后View层仅负责UI渲染和事件转发,业务逻辑完全由Controller处理,符合MVC分层原则。
- 购物车显示增加价格信息并换行,提升排版可读性。
内容的提问来源于stack exchange,提问作者ruscanca
相关产品推荐
相关产品推荐

