/* * File: DrawableString.java * * A DrawableString class with centering capability * * Copyright: Northeast Parallel Architectures Center * */ import java.awt.*; public class DrawableString extends Font { private String string; private Color color; // Does it make sense to have a no-arg constructor? public DrawableString() { super( "SansSerif", Font.BOLD, 18 ); this.string = ""; this.color = Color.black; } public DrawableString( String string ) { this(); this.string = string; } public String getString() { return this.string; } public void setString( String string ) { this.string = string ; } public Color getColor() { return this.color; } public void setColor( Color color ) { this.color = color; } // Variables name, style, and size are inherited from Font: public void setFontName( String name ) { this.name = name; } public void setFontStyle( int style ) { this.style = style; } public void setFontSize( int size ) { this.size = size; } // These methods are for compatibility with DrawablePolygon: public void draw( Graphics g, int x, int y ) { g.drawString( this.string, x, y ); } public void draw( Component c, int x, int y ) { this.draw( c.getGraphics(), x, y ); } public void fill( Graphics g, int x, int y ) { this.draw( g, x, y ); } public void fill( Component c, int x, int y ) { this.fill( c.getGraphics(), x, y ); } // Center this string in the given component: public void centerDraw( Component c ) { if ( this.string == null ) return; // Should we restore the previous color? if ( this.color != null ) c.setForeground( color ); // Get graphics object for this component: Graphics g = c.getGraphics(); // Methods getName(), getStyle(), and getSize() are // inherited from Font: g.setFont( new Font( getName(), getStyle(), getSize() ) ); // Get a FontMetrics object: FontMetrics fm = g.getFontMetrics(); // Determine the width of the component: int componentWidth = c.getSize().width; // Determine the width of the string: int stringWidth = fm.stringWidth( this.string ); // Calculate the x-coordinate of the string: int x = ( componentWidth - stringWidth )/2; // Determine the height of the component: int componentHeight = c.getSize().height; // Calculate the height of *any* string: int ascent = fm.getAscent(); int descent = fm.getDescent(); int stringHeight = ascent + descent; // Calculate the y-coordinate of the string: int y = ( componentHeight - stringHeight )/2 + ascent; // Draw the string at point (x,y): this.draw( g, x, y ); } }