This is a Java Program to Display String in a Rectangle
We have to write a program in Java such that it creates a rectangle and displays a string inside it.
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".
1. Draw a rectangle with required dimensions.
2. Create a string and draw it with proper co-ordinates.
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 */
public class String_Rectangle extends Applet
//Initialize the applet
public void init()
//Function to draw rectangle and string
public void paint(Graphics g)
int wid = 300;
int len = 150;
//Draw a rectangle
//Create a font and draw string
Font myFont = new Font("TimesRoman",Font.BOLD,15);
String s = "String inside Rectangle";
<applet code = String_Rectangle.class width = 500 height = 500>
To compile and execute the program use the following commands :
>>> javac String_Rectangle.java >>> appletviewer String_Rectangle.java
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.
Here’s the run time test cases to draw a string in rectangle for different input cases.
Sanfoundry Global Education & Learning Series – Java Programs.