Java Program to Display String in Rectangle

[ad_1]

This is a Java Program to Display String in a Rectangle

Problem Description

We have to write a program in Java such that it creates a rectangle and displays a string inside it.

Expected Input and Output

For drawing string in a rectangle, we can have the following set of input and output.

To View the String in a Rectangle :

On the execution of the program,
it is expected that a string is displayed inside a rectangle.
Given string is "String inside Rectangle".
Rectangle shape color should be "Red" and string color "Green".

Problem Solution

1. Draw a rectangle with required dimensions.
2. Create a string and draw it with proper co-ordinates.

Program/Source Code

Here is source code of the Java Program to display string in a rectangle. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.

/* Java Program to Display String in a Rectangle */
import java.applet.*;
import java.awt.*;
public class String_Rectangle extends Applet
{
    //Initialize the applet
    public void init()
    {
    setBackground(Color.white);
    }
    //Function to draw rectangle and string
    public void paint(Graphics g)
    {
    g.setColor(Color.red);


    int wid = 300;
    int len = 150;
    //Draw a rectangle
    g.drawRect(100,175,wid,len);


    //Create a font and draw string
    Font myFont = new Font("TimesRoman",Font.BOLD,15);
    g.setFont(myFont);
    g.setColor(Color.green);
    String s = "String inside Rectangle";
    g.drawString(s,150,250);
    }
}
/*
<applet code = String_Rectangle.class width = 500 height = 500>
</applet>
*/

To compile and execute the program use the following commands :

>>> javac String_Rectangle.java
>>> appletviewer String_Rectangle.java

Program Explanation

1. Use drawRect(int x,int y,int width,int length) method of Graphics class to draw a rectangle with dimensions width * length starting from (x,y) co-ordinate.
2. To draw a string use method drawString.

Runtime Test Cases

Here’s the run time test cases to draw a string in rectangle for different input cases.

Test case 1 – To View a String in Rectangle.
java-program-string-in-rectangle

Source link

Leave a Comment