1 /* MovableString.java */ 2 3 import java.awt.*; 4 5 public class MovableString extends MovableObject { 6 7 // Instance variables: 8 private int w, h; 9 protected String s; 10 protected Font f; 11 12 // Constructor: 13 public MovableString( int new_x, int new_y, String new_s ) { 14 // Invoke MovableObject's constructor: 15 super( new_x, new_y ); 16 s = new_s; 17 // A default font: 18 setFont( new Font( "SansSerif", Font.PLAIN, 36 ) ); 19 } 20 21 // Accessors and mutators: 22 public void setString( String new_s ) { 23 s = new_s; 24 } 25 public void setFont( Font new_f ) { 26 f = new_f; 27 } 28 29 // Implement MovableObject.paint( Graphics ): 30 public void paint( Graphics g ) { 31 g.setColor( color ); 32 g.setFont(f); 33 FontMetrics fm = g.getFontMetrics(); 34 w = fm.stringWidth(s); // width of string in current font 35 h = fm.getHeight() - fm.getDescent(); 36 g.drawString( s, x, y + h ); 37 } 38 39 // Implement MovableObject.contains( int, int ): 40 public boolean contains( int some_x, int some_y ) { 41 Rectangle r = new Rectangle( x, y, w, h ); 42 return r.contains( some_x, some_y ); 43 } 44 45 // Implement MovableObject.checkBoundary( Rectangle ): 46 public void checkBoundary( Rectangle r ) { 47 int nx = x + dx, ny = y + dy; 48 if ( (nx < r.x) || (nx + w > r.x + r.width) ) dx = -dx; 49 if ( (ny < r.y) || (ny + h > r.y + r.height) ) dy = -dy; 50 } 51 52 }