控制台程序。
1 import javax.swing.JComponent; 2 import java.util.*; 3 import java.awt.*; 4 import java.awt.geom.*; 5 6 @SuppressWarnings("serial") 7 public class SketcherView extends JComponent implements Observer { 8 public SketcherView(Sketcher theApp) { 9 this.theApp = theApp; 10 } 11 12 // Method called by Observable object when it changes 13 public void update(Observable o, Object rectangle) { 14 // Code to respond to changes in the model... 15 } 16 17 // Method to draw on the view 18 @Override 19 public void paint(Graphics g) { 20 // Temporary code... 21 Graphics2D g2D = (Graphics2D)g; // Get a Java 2D device context 22 23 g2D.setPaint(Color.RED); // Draw in red 24 25 // Position width and height of first rectangle 26 Point2D.Float p1 = new Point2D.Float(50.0f, 10.0f); 27 float width1 = 60; 28 float height1 = 80; 29 30 // Create and draw the first rectangle 31 Rectangle2D.Float rect = new Rectangle2D.Float(p1.x, p1.y, width1, height1); 32 g2D.draw(rect); 33 34 // Position width and height of second rectangle 35 Point2D.Float p2 = new Point2D.Float(150.0f, 100.0f); 36 float width2 = width1 + 30; 37 float height2 = height1 + 40; 38 39 // Create and draw the second rectangle 40 g2D.draw(new Rectangle2D.Float( 41 (float)(p2.getX()), (float)(p2.getY()), width2, height2)); 42 g2D.setPaint(Color.BLUE); // Draw in blue 43 44 // Draw lines to join corresponding corners of the rectangles 45 Line2D.Float line = new Line2D.Float(p1,p2); 46 g2D.draw(line); 47 48 p1.setLocation(p1.x + width1, p1.y); 49 p2.setLocation(p2.x + width2, p2.y); 50 g2D.draw(new Line2D.Float(p1,p2)); 51 52 p1.setLocation(p1.x, p1.y + height1); 53 p2.setLocation(p2.x, p2.y + height2); 54 g2D.draw(new Line2D.Float(p1,p2)); 55 56 p1.setLocation(p1.x - width1, p1.y); 57 p2.setLocation(p2.x - width2, p2.y); 58 g2D.draw(new Line2D.Float(p1, p2)); 59 60 g2D.drawString("Lines and rectangles", 60, 250); // Draw some text 61 62 } 63 64 private Sketcher theApp; // The application object 65 }
其他部分与上一例相同。