// File: TestAwt12.java (Module 9) // // Author: Rahul Simha // Created: October 13, 1998 // // Using FontMetrics. import java.awt.*; class NewFrame extends Frame { String[] words; // List of words to display. int fontsize; // Size of font. // Constructor. public NewFrame (int width, int height, String[] words, int fontsize) { // Retain data and font size. this.words = words; this.fontsize = fontsize; // Set the title and other frame parameters. this.setTitle ("Font metrics"); this.setResizable (true); this.setBackground (Color.cyan); this.setSize (width, height); // Show the frame. this.setVisible (true); } // Override paint(): public void paint (Graphics g) { // Create a Serif font in the given font size. Font f = new Font ("Serif", Font.PLAIN | Font.BOLD, fontsize); g.setFont (f); // Get a FontMetrics instance from the graphics context. FontMetrics fm = g.getFontMetrics(); // Get the height (height of font plus separator). int fontheight = fm.getHeight (); // Size of frame plus insets. Dimension D = this.getSize (); Insets I = this.getInsets (); // Visible drawing area int max_width = D.width - I.left - I.right - 1; int max_height = D.height - I.top - I.bottom - 1; // Start at topleft. int startx = 0 + I.left; // Must add font height since bottom left corner // of font is used as starting point. int y = 0 + I.top + fontheight; int x = startx; for (int i=0; i < words.length; i++) { // Obtain pixel-length of string (with blank) int len = fm.stringWidth (" " + words[i]); if (x + len < max_width) { // If it fits within the current line, draw it g.drawString (" " + words[i], x, y); x += len; } else { // Go to next line. x = startx; y += fontheight; g.drawString (" " + words[i], x, y); x += len; } } } // "paint" } // End of class "NewFrame" public class TestAwt12 { public static void main (String[] argv) { String[] testwords = { "There", "once", "was", "a", "poet", "named", "Heinz", "All", "of", "whose", "poems", "had", "just", "two", "lines." }; NewFrame nf = new NewFrame (600,200, testwords, 35); } }