使用模型-视图-控件结构来开发GUI程序。

下面的程序演示了MVC模式开发的java程序。

其中CircleModel为模型,包含了圆的半径,是否填充,等属性。

CircleView为视图,显示这个圆。

CircleController为控制器,控制圆的大小,以及是否被填充。

 

模型:

 1 package circleMVC;
 2 
 3 import java.awt.Color;
 4 import java.awt.event.*;
 5 import java.util.*;
 6 
 7 public class CircleModel {
 8     //圆半径
 9     private double radius = 20;
10     
11     //是否填充
12     private boolean filled;
13     
14     //颜色
15     private java.awt.Color color;
16     
17     private ArrayList<ActionListener> actionListenerList;
18 
19     public double getRadius() {
20         return radius;
21     }
22 
23     public void setRadius(double radius) {
24         this.radius = radius;
25         processEvent(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "radius"));//当属性值改变是通知监听器
26     }
27 
28     public boolean isFilled() {
29         return filled;
30     }
31 
32     public void setFilled(boolean filled) {
33         this.filled = filled;
34         processEvent(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "filled"));//当属性值改变是通知监听器
35     }
36     
37     
38 
39     public java.awt.Color getColor() {
40         return color;
41     }
42 
43     public void setColor(java.awt.Color color) {
44         this.color = color;
45         processEvent(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "color"));//当属性值改变是通知监听器
46     }
47 
48     public synchronized void addActionListener(ActionListener l){
49         if(actionListenerList == null){
50             actionListenerList = new ArrayList<ActionListener>();
51         }
52         actionListenerList.add(l);
53     }
54     
55     public synchronized void removeActionListener(ActionListener l){
56         if(actionListenerList != null && actionListenerList.contains(l)){
57             actionListenerList.remove(l);
58         }
59     }
60     
61     private void processEvent(ActionEvent e){
62         ArrayList list;
63         
64         synchronized(this){
65             if(actionListenerList == null) return;
66             list = (ArrayList)actionListenerList.clone();
67         }
68         for(int i = 0; i < list.size(); i++){
69             ActionListener listener = (ActionListener)list.get(i);
70             listener.actionPerformed(e);
71         }
72     }
73 }
View Code

相关文章: