承接系列二,修復添加用戶輸入校驗 Bug,新增刪除用戶、修改用戶功能,完成用戶模塊完整 CRUD 閉環。採用 Swing 構建桌面 UI,分層架構:UI → EBI(業務接口) → Factory → VO(值對象)。
private void btnAddActionPerformed(ActionEvent evt) {
// 1. 收集參數
String uuid = tfdUuid.getText();
String name = tfdName.getText();
String pwd = new String(tfdPwd.getPassword());
String pwd2 = new String(tfdPwd2.getPassword());
// 2. 校驗 (修復空指針/空串判斷)
if (uuid == null || uuid.trim().isEmpty()) { showMsg("用戶ID為空"); return; }
if (name == null || name.trim().isEmpty()) { showMsg("用戶名為空"); return; }
if (!pwd.equals(pwd2) || pwd.isEmpty()) { showMsg("兩次密碼不一致或為空"); return; }
int type;
try { type = UserTypeEnum.getTypeByName((String)combType.getSelectedItem()); }
catch (Exception e) { showMsg("請選擇用戶類型"); return; }
// 3. 組裝 VO
UserModel user = new UserModel();
user.setUuid(uuid); user.setName(name); user.setPwd(pwd); user.setType(type);
// 4. 調用業務邏輯
if (UserEbiFactory.getUserEbi().create(user)) back();
else showMsg("用戶已存在");
}
public DeletePanel(JFrame mainFrame, String uuid) {
this.mainFrame = mainFrame; this.uuid = uuid;
initComponents(); myInitData(); // 載入用戶信息並禁用編輯
}
private void myInitData() {
UserModel m = UserEbiFactory.getUserEbi().getSingle(uuid);
tfdName.setText(m.getName()); tfdUuid.setText(m.getUuid());
tfdPwd.setText(m.getPwd()); tfdType.setText(UserTypeEnum.getNameByType(m.getType()));
// 全部 setEditable(false)
}
private void btnDeleteActionPerformed(ActionEvent evt) {
if (UserEbiFactory.getUserEbi().delete(uuid)) back();
else showMsg("用戶不存在");
}
private void myInitData() {
UserModel m = UserEbiFactory.getUserEbi().getSingle(uuid);
tfdUuid.setText(m.getUuid()); tfdUuid.setEditable(false);
tfdName.setText(m.getName());
tfdPwd.setText(m.getPwd()); tfdPwd2.setText(m.getPwd());
// 下拉框先顯示當前類型,再追加其他類型
combType.removeAllItems();
combType.addItem(UserTypeEnum.getNameByType(m.getType()));
for (UserTypeEnum t : UserTypeEnum.values())
if (!t.getName().equals(m.getType())) combType.addItem(t.getName());
}
private void btnUpdateActionPerformed(ActionEvent evt) {
// 校驗邏輯同 AddPanel
// 組裝 VO 調用 ebi.update(user) 成功則 back()
}
private void myInitData() {
List list = UserEbiFactory.getUserEbi().getAll();
userLists.setListData(list.toArray()); // JList 直接顯示 VO
}
// 三個導航按鈕動作
btnToAdd: mainFrame.setContentPane(new AddPanel(mainFrame));
btnToDelete: mainFrame.setContentPane(new DeletePanel(mainFrame, selected.getUuid()));
btnToUpdate: mainFrame.setContentPane(new UpdatePanel(mainFrame, selected.getUuid()));
mainFrame.validate(); // 刷新 UI
UserEbiFactory 隱藏實現類實例化細節。UserModel 攜帶數據跨層,UserCommand (前端) 隔離表單字段。UserTypeEnum 統一用戶類型常量,避免魔術數字。setContentPane 實現面板無縫切換。用戶列表顯示所有記錄,點擊「添加/修改/刪除」跳轉對應面板,操作成功自動返回列表並刷新。數據持久化層 (文件/數據庫) 由 EBI 實現類封裝,UI 層零感知。
下一步將擴展書籍、銷售模塊,引入數據庫持久化替換文件存儲。