Java Program to Display Text in Different Fonts

This is a Java Program to Display Text in Different Fonts

Problem Description

We have to write a program in Java such that it displays text in 10 different fonts.

Expected Input and Output

For displaying text in different fonts, we can have the following set of input and output.

To View the Texts:

On every execution of the program,
it is expected that texts with different fonts are displayed.

Problem Solution

1. Get the list of all fonts available in the system using GraphicsEnvironment.
2. Create random fonts using the list generated.
3. Set the created font to the graphics object.
4. Draw the text using drawString method.

Program/Source Code

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

/* Java Program to Display Text in Different Fonts */
import java.applet.*;
import java.awt.*;
import java.awt.GraphicsEnvironment;
import java.lang.Math;
public class Text extends Applet
{
    String fonts[];
    //Function to get the list of fonts available
    public void init()
    {
    setBackground(Color.white);


    GraphicsEnvironment GE;
        GE = GraphicsEnvironment.getLocalGraphicsEnvironment();
    fonts = GE.getAvailableFontFamilyNames();
    }
    //Function to draw the text
    public void paint(Graphics g)
    {
    int size = fonts.length;
    int pos;
    for(int i=1;i<=10;i++)
    {
        pos = (int)(Math.random()*size);
        Font my_font = new Font(fonts[pos],Font.PLAIN,20);
        g.setFont(my_font);
        g.drawString("Sample Text",100,(i*40));
    }
    }
}
/*
<applet code = Text.class width = 500 height = 600>
</applet>
*/
  1. To compile and execute the program type the following commands :
>>> javac Text.java
>>> appletviewer Text.java

Program Explanation

1. To get the local graphics environment, use the getLocalGraphicsEnvironment method.
2. To get the list of fonts, use getAvailableFontFamilyNames method.
3. Create a font using Font class with parameters font name, type of font and size of font.
4. Set the font to the graphics object using setFont.
5. Draw the string using drawString.

Runtime Test Cases

Here’s the run time test cases to display text in different fonts for different input cases.

Test case 1 – To View Text in Different Fonts.
java-program-text-different-fonts-1

Test case 2 – To View Text in Different Fonts.
java-program-text-different-fonts-2

Source link

Leave a Comment