import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class ViewGraph extends JPanel implements Observer {
	Model model;

	public ViewGraph(Model model) {
		try {
			this.model = model;
			jbInit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void jbInit() throws Exception {
		this.setBackground(Color.white);
		this.setBorder(new TitledBorder(
			BorderFactory.createLineBorder(Color.black, 1),
			"视图2"));
	}

	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 / 3;
        int r = 10;    
		for (int i = 0; i < model.size(); i++) {
			Data data = model.getData(i);
			int value = data.value;
			int dx = 3;
			        
			g.fillRect(sx, sy, value+20, r);
			g.drawString(data.name, 25, sy);
            sy=sy+30;
		}
	}

	// 当模型数据发生改变时，会自动调用此方法来刷新图形 
	public void dataUpdate(Model model) {	
		this.model = model;
		repaint();
	}

}
