Java AWT Drawing Strings Frame


Graphics class allows us to draw strings on the frame with its method drawString(). Following is the signature.

void drawString(String str1, int x, int y): x and y are the coordinates where the string str1 is to be drawn on the frame.

Following program illustrates.

import java.awt.*;
public class StringsDrawing extends Frame
{
  public StringsDrawing()
  {
    setTitle("Practicing Strings");
    setSize(300, 350);
    setVisible(true);
  }
  ublic void paint(Graphics g)
  {
    g.drawString("Hello World", 60, 80);
    g.drawString("How do you do?", 60, 100);
    g.drawString("Please accept greetings", 60, 120);
  } 
  public static void main(String args[])
  {
    new StringsDrawing();
  }
}	

Java AWT Drawing Strings Frame

setSize(300, 350);

To draw strings, a frame of width 300 pixels and height 350 pixels is created. The frame you get do not close when clicked over the close icon on the title bar of the frame. It requires extra code.

g.drawString("Hello World", 60, 80);


The string "Hello World" is drawn on the frame at x-coordinate of 60 pixels and y-coordinate of 80 pixels. Infact, the first letter H is drawn at 60, 80 coordinates and other letters of the string follows automatically one after another. It is the base of the H. If a line is drawn at the same coordinates, it becomes underline. A program Centered Text with Underline deals with string centering in frame and underlining the text.

The y coordinate in the drawString() methods is incremented by 20 pixels to get the line below the previous.

Leave a Comment

Your email address will not be published.