MVC: GraphView.java

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

public class GraphView extends JPanel implements Observer {
    /**
     * The Model (Account) we are observing
     */
    private Model model;

    /**
     * Our drawing parameters, try to do things in terms of this
     */
    Rectangle barLoc = new Rectangle (20, 20, 200, 40);

    public GraphView (Model model) {
	// Stash arg
	this.model = model;

	// Sign us up as Observer
	model.addObserver (this);

	// Set up our panel
	setBorder (new TitledBorder ("View"));
    }

    /**
     * This will be called by our Model
     */
    public void update (Observable observable, Object object) {//*1 Catch callback from model, and just repaint ourself
	repaint(); //*1
    }

    public void paintComponent (Graphics g) { //*2 We call model for the actual data
	super.paintComponent(g);
	Graphics2D g2 = (Graphics2D) g;
	
	int balance = model.getBalance (); //*2
	int range = 2000;
	if (balance>range) balance = range;
	if (balance< -range) balance = -range;

	// Bar for balance
	if (balance<0) { //*3 Draw graphic representation
	    g2.setColor (Color.RED); //*3
	    g2.fill (new Rectangle ( //*3
		barLoc.x + ((balance+range) * barLoc.width/2) / range, //*3
		barLoc.y, //*3
		((-balance) * barLoc.width/2) / range, //*3
		barLoc.height)); //*3
	}
	else { //*3
		g2.setColor (Color.GREEN); //*3
		g2.fill (new Rectangle ( //*3
		    barLoc.x + barLoc.width/2, //*3
		    barLoc.y, //*3
		    (balance * barLoc.width/2) / range, //*3
		    barLoc.height)); //*3
	}

	// Outline
	g2.setColor (Color.BLACK);
	g2.draw (barLoc); //*3

	// Zero line
	g2.drawLine (barLoc.x + barLoc.width/2, barLoc.y-10, //*3
	     barLoc.x + barLoc.width/2, barLoc.y+barLoc.height+10); //*3

	// Legends
	int ylegend = barLoc.y + barLoc.height + 15;
	g2.drawString ("-" + String.valueOf (range), barLoc.x-10, ylegend);
	g2.drawString ("0", barLoc.x + barLoc.width/2 -2, ylegend);
	g2.drawString (String.valueOf (range), barLoc.x + barLoc.width -10, ylegend);
    }

    public Dimension getPreferredSize () {
	return new Dimension (barLoc.x + barLoc.width + barLoc.x,
	    barLoc.y + barLoc.height + barLoc.y);
    }
}
[download file]