//Enter background color: blue //Enter font name: SansSerif //Enter font size: 50 //Enter message: THINK // // ascent+descent = height of message; // divide by 2 and leave that much space left/right/up/down // if color is not valid; use black // Prompt user to enter background color and determine matching Color object // Prompt user to enter the font name // Prompt user to enter the font size // Prompt user to enter the message // Create a window labeled Display Message // Create the desired font and obtain FontMetrics object for it // compute width and height of message and ascent of font // display window ; sizing it to fit the message // draw rectangle in specified background color // display message in white centered // repaint window import java.awt.*; import ohjava.*; public class DisplayMessage { public static void main (String args[]) { DrawableFrame df; Graphics g; Graphics g2; Font f; FontMetrics fm; String fontName; String message; int ascent; int fontSize; int messageHeight; int messageWidth; Color backgroundColor; SimpleIO.prompt("Enter background color: "); backgroundColor = convertToColor(SimpleIO.readLine()); SimpleIO.prompt("Enter font name: "); fontName = SimpleIO.readLine(); SimpleIO.prompt("Enter font size: "); fontSize = Integer.parseInt(SimpleIO.readLine()); SimpleIO.prompt("Enter message: "); message = SimpleIO.readLine(); df = new DrawableFrame("Display Message"); f = new Font(fontName, Font.PLAIN, fontSize); df.show(); df.setSize(1,1); g = df.getGraphicsContext(); fm = g.getFontMetrics(f); messageWidth = fm.stringWidth(message); ascent = fm.getAscent(); messageHeight = ascent + fm.getDescent(); df.show(); df.setSize(messageWidth+messageHeight, 2*messageHeight); g = df.getGraphicsContext(); g.setColor(backgroundColor); g.fillRect(0,0,messageWidth+messageHeight, 2*messageHeight); g.setColor(Color.white); g.setFont(f); g.drawString(message,messageHeight/2, messageHeight/2 + ascent); df.repaint(); } private static Color convertToColor(String colorName) { if (colorName.equalsIgnoreCase("blue")) return Color.blue; else if (colorName.equalsIgnoreCase("cyan")) return Color.cyan; else if (colorName.equalsIgnoreCase("darkGray")) return Color.darkGray; else if (colorName.equalsIgnoreCase("gray")) return Color.gray; else if (colorName.equalsIgnoreCase("green")) return Color.green; else if (colorName.equalsIgnoreCase("lightGray")) return Color.lightGray; else if (colorName.equalsIgnoreCase("magenta")) return Color.magenta; else if (colorName.equalsIgnoreCase("orange")) return Color.orange; else if (colorName.equalsIgnoreCase("pink")) return Color.pink; else if (colorName.equalsIgnoreCase("red")) return Color.red; else if (colorName.equalsIgnoreCase("white")) return Color.white; else if (colorName.equalsIgnoreCase("yellow")) return Color.yellow; else return Color.black; } }