public class Data { public int value; public String name; }
现在来建立一个Model: /* file&: Model.java */
import java.util.*; public class Model { ArrayList data = new ArrayList(); ArrayList observer = new ArrayList(); public Model() { super(); } public Model(int[] value, String[] name) { for ( int i = 0; i< value.length; i++ ) { addData(value[i],name[i]); } } public Model(Data[] data) { for ( int i = 0; i< data.length; i++ ) { addData(data[i]); } } public void addData(int value, String name) { Data data = new Data(); data.value = value; data.name = name; this.data.add(data); } public void addData(Data data) { this.data.add(data); } public Data getData(int idx) { return (Data)(data.get(idx)); }
public int size() { return data.size(); } public void registerObserver(Observer o) { observer.add(o); } public void removeObserver(Observer o) { observer.remove(o); } public void changeModel(Model model) { data.clear(); for (int i=0; i { this.addData(model.getData(i)); } dataUpdate(); } PRivate void dataUpdate() { for (Iterator i = observer.iterator(); i.hasNext(); ) { Observer o = (Observer)(i.next()); o.dataUpdate(this); } } }
public void paintComponent(Graphics g) { super.paintComponent(g); if ( model == null ) return; int x = 20,y = 50; int h = g.getFontMetrics().getHeight(); for ( int i=0; i< model.size(); i++ ) { Data data = model.getData(i); g.drawString(data.name,x,y); y+=h; g.drawString(String.valueOf(data.value),x,y); y+=h; } } public void dataUpdate(Model model) { /**@todo: Implement this Observer method*/ this.model = model; repaint(); } } /* file&: View2.java */ import javax.swing.*; import java.awt.*; import javax.swing.border.*; public class View2 extends JPanel implements Observer { Model model;
public void paintComponent(Graphics g) { super.paintComponent(g); if ( model == null ) return; int x = 20,y = 50; int h = g.getFontMetrics().getHeight(); int width = this.getWidth(); int height = this.getHeight(); int sy = height / model.size(); int sx = width/ 2; for ( int i=0; i< model.size(); i++ ) { Data data = model.getData(i); int value = data.value; int dx = 3; int r = 3; Color c = new Color((int)(255*Math.random()),(int)(255*Math.random()),(int)(255*Math.random())); int cx = sx; int cy = y+i * sy; for ( int j=0;j {