import java.awt.*; import javax.swing.*; import java.awt.event.*; // A simple model with one piece of data, setters & getters, and an action method public class Model { private int x=15; // the model data private View view; // the model's view public Model() { view = new View(this); // create a view passing itself as the model } public int position() {return x;} // access for View public void hop() {x+=20; } // change model data // change model data over some time public void action() { // let the ball move a number of times for (int i=5; i<200; i+=20) { hop(); // make a change to the model view.repaint(); // ask view to refresh itself // wait a bit in so that intermediate steps can be seen // otherwise repaint collects all updates for (int j=0; j<250000; j++) Math.pow(2, 64); } } public static void main(String args[]) { Model model=new Model(); // create a new model (creates its own view) // wait a bit for view to be fully displayed for (int j=0; j<500000; j++) Math.pow(2, 64); model.action(); // change model data over some time } } class View extends JFrame { public View(Model model) { super("Swing Example"); // set window title setSize(300, 170); // set window size // make window react to close box event addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); // replace content pane with new playfield component setContentPane(new PlayfieldPanel(model)); // show window setVisible(true); } } // A new Swing component responsible for showing the playing field // inherits from JPanel to obtain background & double buffering class PlayfieldPanel extends JPanel { private Model model; // the model to be visualized public PlayfieldPanel(Model m) // accepts model from view { model=m; // save model for later access setBackground(Color.green.darker()); // grass is green... } // this is called whenever the playfiled is redrawn (e.g., on repaint) public void paintComponent(Graphics g) { super.paintComponent(g); // draw (green) background first g.setColor(Color.white); // set white foreground color g.fillOval(model.position(), 50, 35, 35); // draw ball at a position obtained from model } }