Fonts Available in Java AWT
Last Updated :
15 Nov, 2023
We know that AWT stands for ABSTRACT WINDOW TOOLKIT. For, Example when we want to draw a string in the AWT in Frame we use the method Graphics.drawString(String str, int x_coordinate, int y_coordinate). Now use the Font class for the string to display in the type of font you want. As it is difficult to remember all the font names we can get the font names that are available in the AWT with the help of GraphicsEnvironment class in AWT.
After importing the GraphicsEnvironment in the AWT package in java. we need to import the getLocalGraphicsEnvironment() In the getLocalGraphicsEnvironment() we have to create an object for that and with the help of the object we have to call the getAvailableFontFamilyNames().
Program to Fetch Font Family Names in the AWT
By using getAvailableFontFamilyNames() you can get the array of all the available fonts in AWT, which have been displayed on the console.
Java
import java.awt.*;
class GFG {
public static void main(String[] args)
{
System.out.println( "To Know the available font family names" );
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
System.out.println( "Getting the font family names" );
String fonts[] = ge.getAvailableFontFamilyNames();
for (String i : fonts) {
System.out.println(i + " " );
}
}
}
|
Output:
We will get all the available font family names.
Explanation of the above Program:
- Using the instance of GraphicsEnvironment.getLocalGraphicsEnvironment().
- Fetching the array of Available fonts into the String fonts[] with the help of getAvailableFontFamilyNames().
Now we can use any of the font family names and we can use it in the Font class that is present in the AWT package in Java.
Usage of font class with the help of font family names in AWT
Now let’s see an example program to learn about the usage of the font family in Java.awt package.
Java
import java.awt.*;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class GFG extends Frame {
GFG(){
this .addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit( 0 );
}
});
}
public void paint(Graphics g){
g.setColor(Color.GREEN);
g.setFont( new Font( "Algerian" , Font.BOLD, 50 ));
g.drawString( "GEEKS FOR GEEKS" , 100 , 200 );
}
public static void main(String args[]){
GFG obj = new GFG();
obj.setTitle( "GeeksForGeeks" );
obj.setSize( 600 , 600 );
obj.setVisible( true );
}
}
|
Output:
We use the AWT Frame with the title GeeksForGeeks and We have used the font style Algerian using the fontClass.
This is about Knowing the FontFamily in AWT and using it in the program for drawing a string in the AWT.
Explanation of the above Program:
- GFG obj to create a window layout to display data.
- Set the different parameters like Title, Size, Visible, etc.
- paint() method to create the Graphics of the text “Geeks For Geeks”.
Share your thoughts in the comments
Please Login to comment...