一起学习
为了更好理解MVC,在这里我给出一个简单例子.
共有4个java类,你可以Run AccountFrame.java.
//AccountModel.java
package com.newmodern.mvc;
import java.util.*;
public class AccountModel extends Observable{
private double dBalance;
private String AccountID;
public AccountModel(String AccountID, double dBalance){
this.AccountID = AccountID;
this.dBalance = dBalance;
}
public void deposit(double dBalance){
this.dBalance =dBalance;
setChanged();
notifyObservers(this);
}
public void substract(double dBalance){
this.dBalance-=dBalance;
setChanged();
notifyObservers(this);
}
public double getBalance(){
return dBalance;
}
public void mynotifyObservers(){
setChanged();
notifyObservers(this);
}
}
|
//AccountView.java
package com.newmodern.mvc;
import java.util.*;
import java.awt.*;
public class AccountView implements Observer{
TextField txtBalance;
AccountModel am;
public AccountView (AccountModel am){
this.am = am;
am.addObserver(this);
txtBalance = new TextField(10);
}
public void update(Observable o,Object arg){
txtBalance.setText(String.valueOf(am.getBalance()));
}
public TextField getTextField(){
return txtBalance;
}
}
|
package com.newmodern.mvc;
import java.awt.event.*;
public class AccountController implements ActionListener{
AccountFrame accountFrame;
public AccountController(AccountFrame af){
this.accountFrame = af;
}
public void actionPerformed(ActionEvent ae) {
String sCommand = ae.getActionCommand();
if (sCommand.equals("deposit")){
System.out.println("Action: deposit");
accountFrame.am.deposit(accountFrame.getValue());
} else if(sCommand.equals("sub")){
System.out.println("Action: substract");
accountFrame.am.substract(accountFrame.getValue());
}
}
}
|
package com.newmodern.mvc;
import java.awt.*;
import java.awt.event.*;
public class AccountFrame extends Frame {
AccountController ac;
AccountView av;
AccountView av1;
AccountModel am;
TextField txtValue;
Button btnDeposit;
Button btnSub;
public AccountFrame (String sTitle)
{
super(sTitle);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
dispose();
System.exit(0);
}
});
ac = new AccountController(this);
am = new AccountModel(sTitle,0);
av = new AccountView(am);
av1 = new AccountView(am);
setLayout(new GridLayout(4,2));
txtValue = new TextField(10);
btnDeposit = new Button("deposit");
btnSub = new Button("sub");
add(new Label("value:"));
add(txtValue);
add(new Label("balance:"));
add(av.getTextField());
add(new Label("balance1:"));
add(av1.getTextField());
add(btnDeposit);
add(btnSub);
btnDeposit.addActionListener(ac);
btnSub.addActionListener(ac);
//setSize(200,200);
pack();
show();
am.mynotifyObservers();
}
public double getValue() throws NumberFormatException {
double value = Double.parseDouble(txtValue.getText());
return value;
}
public static void main(String args[])
{
String id = "100";
new AccountFrame(id);
}
}
|
下载本文示例代码
为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例为了更好理解MVC一例
阅读(152) | 评论(0) | 转发(0) |