起初这个应用程序是在没有数据库的情况下构建的。它运行良好。 但是在我修改它以使用数据库之后,在调用存款或删除帐户功能时,视图变得没有响应。但数据库事务正常工作。我不知道为什么请帮帮我
这是研究所
public class Institute extends Observable {
private String name;
private String contactPerson;
private String telephone;
private String address;
private List<Account> accountList;
private static Institute instance;
private List<Account> getAccountsFromDB() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Lab12WithDBPU");
EntityManager em = emf.createEntityManager();
List<Account> accounts = em.createNamedQuery("Account.findAll").getResultList();
return accounts;
}
private Institute(){
accountList = getAccountsFromDB();
}//end cons
public static Institute getInstance(){
//follow singleton design pattern
if (instance == null) {
instance = new Institute();
}//end if
return instance ;
}//end method
public static int addData (Account e) {
persist(e);
return 1;
}
public static void removeData (Account e) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Lab12WithDBPU");
EntityManager em = emf.createEntityManager();
Account employee = em.find(Account.class, e.getAccountId());
em.getTransaction().begin();
em.remove(employee);
em.getTransaction().commit();
}
public void closeAccount(String accountId) throws IllegalArgumentException {
Account deleteAccount = findAccountById(accountId);
//not found the account object
if (deleteAccount == null) {
throw new IllegalArgumentException("The Account ID not found");
}//end if
//can't delete current that have saving
if (deleteAccount.getAccountType() == AccountType.CURRENT && this.accountList.size() > 1) {
throw new IllegalArgumentException("Can't Delete \"Current\" Account Type that have \"Saving\" Accounts Type");
}//end method
//can't delete current that have balance > 0
if (deleteAccount.getAccountType() == AccountType.CURRENT && deleteAccount.getBalance() != 0) {
throw new IllegalArgumentException("The Balance of \"Current\" Account Type Must be 0 to Delete");
}//end method
//get the current to deposit
Account currentAccount = accountList.get(0);
//if selected account to delete has balance > 0 then deposite the account from the list, else don't
if (deleteAccount.getBalance() > 0) {
currentAccount.deposit(deleteAccount.getBalance());
}//end if
accountList.remove(deleteAccount);
deleteAccount.notifyAfterDelete();
removeData(deleteAccount);
}//end method
public void createAccount(String accountId, AccountType accountType) throws IllegalArgumentException {
//check duplication
if ( isAccountIdAlreadyExist(accountId) ) {
throw new IllegalArgumentException("This Account ID Already Exsist");
}//end if
//must open current first
if ( this.accountList.isEmpty() && accountType != AccountType.CURRENT ) {
throw new IllegalArgumentException("Must Open \"Current\" Account Type First");
}//end if
//current can have only one
if ( !this.accountList.isEmpty() && accountType == AccountType.CURRENT ) {
throw new IllegalArgumentException("Cannot Open Multiple \"Current\" Accounts Type");
}//end if
//create object
Account account = new Account(0, accountId, accountType );
accountList.add(account);
//register the views with the model in case of the account have just create after run
for (Observer observer : RensselearBankSystem.MODEL_OBSERVER_LIST) {
account.addObserver(observer);
}//end for
//tell the view to update
account.notifyAfterCreate();
addData(account);
}//end method
public String getTotalBalance(){
String result = "";
for (Account account : this.accountList) {
result += account.toString() +"\n";
}//end for
return null;
}//end method
private boolean isAccountIdAlreadyExist(String accountId) {
if (findAccountById(accountId)!=null)
return true;
return false;
}//end method
public List<Account> getAccountList() {
return this.accountList;
}//end method
public Account findAccountById(String accountId) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Lab12WithDBPU");
EntityManager em = emf.createEntityManager();
return em.find(Account.class,accountId);
}//end method
public static void persist(Object object) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Lab12WithDBPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try {
em.persist(object);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
} finally {
em.close();
}
}
}//end class
这是帐户类
@Entity
@NamedQueries({
@NamedQuery(name = "Account.findAll", query = "SELECT e FROM Account e")})
public class Account extends Observable implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String accountId;
private Integer odLimit;
private Integer balance;
private Integer typeCode;
private AccountType accountType;
public Account() {
}
public Account(Integer balance, String accountID, AccountType accountType) {
odLimit = accountType == AccountType.CURRENT ? 2000 : 0 ;
this.balance = balance;
this.accountId = accountID;
this.accountType = accountType;
if(this.accountType.equals(AccountType.CURRENT))
typeCode = 1;
else
typeCode = 2;
}//end cons
public void deposit(Integer amount) throws IllegalArgumentException{
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Lab12WithDBPU");
EntityManager em = emf.createEntityManager();
Account depositAccount = em.find(Account.class, this.accountId);
em.getTransaction().begin();
//amout must be > 0 to deposit
if (amount <= 0) {
throw new IllegalArgumentException("The Amount must be more than 0");
}//end if
this.balance += amount;
depositAccount.balance += amount;
//tell the views
setChanged();
notifyObservers();
em.getTransaction().commit();
}//end method
public static int addData (Account e) {
persist(e);
return 1;
}
public void notifyAfterCreate(){
System.out.println(this.toString());
System.out.println("notifyAfterCreate");
//tell the views
setChanged();
notifyObservers();
}//end method
public void notifyAfterDelete(){
System.out.println(this.toString());
System.out.println("notifyAfterDelete");
//tell the views
setChanged();
notifyObservers();
}//end method
@Override
public String toString() {
return "[" +this.accountId +", " +this.accountType +", " +this.balance +"]";
}//end method
public String getId() {
return accountId;
}
public void setId(String accountId) {
this.accountId = accountId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (accountId != null ? accountId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Account)) {
return false;
}
Account other = (Account) object;
if ((this.accountId == null && other.accountId != null) || (this.accountId != null && !this.accountId.equals(other.accountId))) {
return false;
}
return true;
}
public Integer getBalance() {
return balance;
}//end method
public String getAccountId() {
return accountId;
}//end method
public AccountType getAccountType() {
return accountType;
}//end method
public static void persist(Object object) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Lab12WithDBPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try {
em.persist(object);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
} finally {
em.close();
}
}
}
这是视图
public class StudentView extends javax.swing.JFrame implements Observer {
/**
* Creates new form StudentView
*/
public StudentView() {
System.out.println("init admin");
initComponents();
setComponentHandles();
JTableManager.initTable(jTable_studentView, Institute.getInstance().getAccountList());
registerView(); // register view for the old account from database
}//end cons
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() { .....
}
// Variables declaration - do not modify
private javax.swing.JButton jButton_deposit;
private javax.swing.JButton jButton_withdraw;
private javax.swing.JLabel jLabel_amout;
private javax.swing.JLabel jLabel_selectedAccount;
private javax.swing.JLabel jLabel_studentInput;
private javax.swing.JLabel jLabel_studentView;
private javax.swing.JLabel jLabel_total;
private javax.swing.JPanel jPanel_studentInput;
private javax.swing.JPanel jPanel_studentView;
private javax.swing.JPanel jPanel_summary;
private javax.swing.JScrollPane jScrollPane_studentView;
private javax.swing.JTable jTable_studentView;
private javax.swing.JTextField jTextField_amout;
private javax.swing.JTextField jTextField_selectedAccount;
private javax.swing.JTextField jTextField_total;
// End of variables declaration
@Override
public void update(Observable o, Object arg) {
//call support method
JTableManager.initTable(this.jTable_studentView, Institute.getInstance().getAccountList());
System.out.println("Student update");
//update total after add/remove change the account
updateTotal();
}//end method
private void setComponentHandles() {
//register observer with the components
this.jTable_studentView.addMouseListener(new SelectStudentViewTableRowListener(this));
this.jButton_deposit.addActionListener( new DepositListener(this) );
this.jButton_withdraw.addActionListener( new WithdrawListener(this) );
}//end method
private void updateTotal() {
List<Account> accountList = Institute.getInstance().getAccountList() ;
int sum = 0;
for (Account account : accountList) {
sum += account.getBalance() ;
}//end for
this.jTextField_total.setText("" +sum);
}//end method
/*
getters, setters
*/
private void registerView() {
List<Account> accountList = Institute.getInstance().getAccountList();
for(Account account : accountList){
account.addObserver(this);
System.out.println(account.getAccountId()+"add observer student\n");
}
}
} //结束课
这是主要的课程
public class RensselearBankSystem {
//list of the views to accessed by controllers and models
public static final List<Observer> MODEL_OBSERVER_LIST = new ArrayList<Observer>();
public static void main(String[] args) {
StudentView studentView = new StudentView();
AdministratorView administratorView = new AdministratorView();
//set position of second frame
Point point = studentView.getLocation();
point.y += 340;
administratorView.setLocation(point);
//add the views to the list
System.out.println("start add to list");
RensselearBankSystem.MODEL_OBSERVER_LIST.add(studentView);
RensselearBankSystem.MODEL_OBSERVER_LIST.add(administratorView);
System.out.println("finish add to list");
studentView.setVisible(true);
administratorView.setVisible(true);
}//end main
}//end class
代码非常长所以,我上传了整个项目click to download my netbeans project