Updated June 7, 2023
Introduction to Java Font
Java Font is a class that represents a font used in Graphical User Interfaces (GUIs) in the Java programming language. It defines how text will be displayed on a GUI component, including its font, size, and style. The font class has a number of constructors that let developers create multiple fonts with various attributes. The syntax for creating a font object is
Font font = new Font(String name, int style, int size)
where,
- name is the font name
- style is the style of the font (bold, italic, etc.)
- size is the font size in points
Key Takeaways
- Fonts are essential to any graphical user interface, and Java provides an extensive set of font-related classes and methods.
- The Font class in Java allows developers to create and manipulate font objects and set font properties.
- Java’s FontRenderContext class provides a platform-independent way to measure.
- Understanding the different types of fonts, such as serif, sans-serif, and monospace, can help developers choose the right font for their applications.
What Are the Types of Java Font?
The right font usage can make all the difference when creating Graphical User Interfaces (GUIs) in Java programming. Its fonts are the cornerstone of any GUI’s textual elements, including text labels, buttons, and menus. Developers working with Java can access various fonts, divided into two main categories: physical and logical.
1. Physical Fonts
Physical fonts are pre-installed on the computer’s operating system and used by Java applications. All of the system’s physical fonts are accessible through the Java platform. The Font.createFont() method can load the actual fonts into the program. The above method takes a font file as input and produces a font object the application can use.
These fonts transform character sequences into glyph sequences using font technologies like TrueType Fonts (TTF) and PostScript Type 1 Font. All Java implementations must support TTF. Only a few writing systems, such as Latin, Japanese, and Basic Latin, are supported by physical fonts.
2. Logical Fonts
All systems that support the Java platform will undoubtedly have access to the logical fonts. The logical fonts are a collection of five font families, each with distinctive qualities, rather than actual font files. Serif, SansSerif, Monospaced, Dialogue, and DialogInput are the five font families.
The logical font names are converted to physical fonts by the JRE. Each logical font name maps to multiple physical fonts to support a broad range of characters.
What Are the Font Faces and Names?
Font faces and names are key components of the Java Font class. The font name is a string used to identify the font, and the family name is a general name used to identify a group of font faces. A font face is a typeface used for rendering a specific font.
Logical Font Name
Serif, SansSerif, Monospaced, Dialogue, and DialogInput are the five font families the Java platform offers. A logical font name is a name that is compatible with any device. The Java runtime environment maps the logical font names and the physically installed fonts on the system.
Example
Font font = new Font("Serif", Font.BOLD, 12);
In this example, the logical font name is “Serif,” which maps to a physical font on the system.
Font Face Name
An individual font style within a font family is referred to by its font face name. Each font family may contain several font faces with different styles, like bold or italic. Each font family has a unique set of font face names, and depending on the system, they may only sometimes be available.
Example
Font font = new Font("Serif", Font.BOLD, 12);
The font face name, in this instance, “Bold,” designates that the font should be displayed in bold style.
Family Name
A family name is a collective term used to describe a collection of font faces. A font family comprises various font faces with the same x-height and stroke width. Font faces are categorized using family names, which are typically connected to a specific font style or genre.
Example
Font font = new Font("Serif", Font.BOLD, 12);
The family name used in the example mentioned above is “Serif,” which encompasses all serif font faces.
Fields of Font Class
Java’s Font class is an effective tool for representing and controlling fonts in graphical user interfaces. The Font class contains many fields that let developers alter the font, size, and style of text that the GUI component displays. The fields available in the Font class are explained in great detail below.
1. Static int BOLD
The BOLD field is a static int that represents the bold font style. The text results in bold when this field is used to create a font object.
2. Static int CENTER_BASELINE
The CENTER_BASELINE field is a static int that represents the foundation for arranging text in ideographic characters, including Chinese, Japanese, and Korean. It specifies the center baseline of the text, which is used to align characters vertically.
3. Static string constant DIALOG
The DIALOG field is a static string constant representing the “Dialog” logical font’s canonical family name. It creates a Font object with the “Dialog” font family.
4. Static string constant DIALOG_INPUT
The DIALOG_INPUT field is a static string constant representing the “DialogInput” logical font’s family name. It creates a Font object with the “DialogInput” font family.
5. Static int HANGING_BASELINE
The HANGING_BASELINE field is a static int denoting the starting point for text layout in Devanigiri and related scripts. It specifies the baseline of characters that hang below the line, such as letters with descenders.
6. Static int ITALIC
The ITALIC field is a static int that represents the italic font style. This field creates a font object, and the text results in an italicized style.
7. Static int LAYOUT_LEFT_TO_RIGHT
The LAYOUT_LEFT_TO_RIGHT field is a static int that indicates to layoutGlyphVector that, according to Bidi analysis, the text is left to right. It is used to give the text direction in a text layout.
8. Static int LAYOUT_NO_LIMIT_CONTEXT
The LAYOUT_NO_LIMIT_CONTEXT field is a static int used as a flag for layoutGlyphVector. It indicates that text in the char array that extends past a specific limit should not be examined. It is utilized to limit the scope of text that is examined in a text layout.
9. Static int LAYOUT_NO_START_CONTEXT
This field is used as a flag in the layoutGlyphVector method to indicate that the developer should not look at the text in the char array first before the specified start. This can be useful when laying out text with a large amount of additional formatting or metadata at the beginning of the text block that isn’t relevant to the layout.
10. Static int LAYOUT_RIGHT_TO_LEFT
According to Bidi analysis, this field is used as a flag in the layoutGlyphVector method to indicate that the text is right-to-left. It can be useful when laying out text in languages such as Arabic or Hebrew, read from right to left.
11. Static string MONOSPACED
This field represents the logical typeface “Monospaced” and has a String constant representing its canonical family name. A monospaced font is one where every character has the same width, which can help display code or other text types where character alignment is essential.
12. Static string Name
This field is a function that returns the logical name of the font. The logical name of the font is the name that identifies it in a font database and may be different from the font’s display name.
13. Static int PLAIN
This field represents a simple, timeless design of the font. It is the default style for fonts and can be used for many applications.
14. Static float pointSize
This field represents the font’s point size and is expressed as a float. The point size of a font is nothing but the size at which it is designed to be displayed on a given screen or printed on a page.
15. Static int ROMAN_BASELINE
This field represents the most common basis line for text layout in Roman scripts. It is used to determine the baseline of a font when it is being laid out on a page.
16. Static string SANS_SERIF
This field represents the logical font “SansSerif” and has a String constant representing its canonical family name. A sans-serif font does not have small lines or serifs at the end of the strokes of the letters, and it is often used for modern and clean designs.
17. Static string SERIF
This field represents the logical typeface “Serif” and has a String constant representing its canonical family name. A serif font has small lines or serifs at the end of the letters’ strokes, and is often used for more traditional designs.
18. Protected int Size
This field represents the font’s point size and is expressed as an integer. It is protected, meaning that subclasses of the Font class can only access it.
19. Protected int Style
This field represents the font style supplied to the function Object(). It is protected, meaning that subclasses of the Font class can only access it.
20. Static int TRUETYPE_FONT
This field is a constant to identify a TrueType font resource. TrueType is a popular digital font technology developed by Apple Computer and widely adopted for fonts on Windows and Macintosh computers.
21. Static int TYPE1_FONT
This field is a constant that can be used to find a font resource with the Type 1 font family. Type 1 fonts are a format for digital fonts developed by Adobe Systems and are commonly used in professional graphic design and printing.
Constructors of Font Class
#1 Font(Font font)
The first constructor of the Font class takes an existing Font object as an argument and creates a new Font object with the same properties. This is helpful when you want to develop a new Font object with the same attributes as an existing Font object.
Example
// Creating a new font object
Font font1 = new Font("Arial", Font.PLAIN, 12);
// Using the existing font object to create a new font object
Font font2 = new Font(font1);
In this example, we create a new Font object named “font1” with the name “Arial“, a plain style, and a size of 12 points. Then, we use the existing “font1” object to create a new Font object named “font2” with the same attributes.
#2 Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)
The second constructor of the Font class takes a Map object that contains font attributes as key-value pairs. It creates a new Font object with the specified properties.
Example
// Creating a Map object with font attributes
Map<AttributedCharacterIterator.Attribute, Object> fontAttributes = new HashMap<>();
fontAttributes.put(TextAttribute.FAMILY, "Times New Roman");
fontAttributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
fontAttributes.put(TextAttribute.SIZE, 16);
// Creating a new font object using the map of attributes
Font font3 = new Font(fontAttributes);
In this example, we create a Map object named “fontAttributes” that contains font attributes such as family, weight, and size. Then, we use this Map object to create a new Font object named “font3” with the specified properties.
#3 Font(String name, int style, int size)
The third constructor of the Font class takes three arguments: font name, font style, and font size. It creates a new Font object with the specified attributes.
Example
// Creating a new font object using font name, style, and size
Font font4 = new Font("Courier New", Font.BOLD | Font.ITALIC, 18);
In this example, we create a new Font object named “font4” with the name “Courier New“, a bold and italic style, and a size of 18 points.
Output
All three constructors of the Font class create a new Font object with the specified attributes. The resulting font object is useful for setting the GUI component’s font.
Methods of Font Class
1. canDisplay(char c)
This method determines whether the specified Font contains a glyph for the requested character.
2. canDisplay(int codePoint)
This method determines whether the specified Font contains a glyph for the requested Unicode code point.
3. canDisplayUpTo(char[] text, int start, int limit)
This method indicates whether the provided text can be displayed using this font, starting at the start index and ending at the limit index.
4. canDisplayUpTo(CharacterIterator iter, int start, int limit)
This method indicates whether the text defined by the CharacterIterator iter, starting at the start index and ending at the limit index, can be displayed using this font.
5. canDisplayUpTo(String str)
This method indicates whether the provided string can be displayed using this font.
6. createFont(int fontFormat, File fontFile)
This method creates a new Font that returns using the provided font type and specified font file.
7. createFont(int fontFormat, InputStream fontStream)
This method creates a new Font that returns using the provided font type and specified font stream.
8. createGlyphVector(FontRenderContext frc, char[] chars)
This method converts the characters in the array to glyphs using this font’s Unicode cmap to build a GlyphVector.
9. createGlyphVector(FontRenderContext frc, CharacterIterator ci)
This method converts the characters in the CharacterIterator to glyphs using this font’s Unicode cmap to build a GlyphVector.
10. createGlyphVector(FontRenderContext frc, String str)
This method converts the characters in the specified string to glyphs using this font’s Unicode cmap to build a GlyphVector.
11. deriveFont(float size)
This method creates a new font object with the same font face, style, and transform as this font but with a new point size specified by the size parameter.
12. getFamily()
This method gets the family name of this font.
13. getSize()
This method gets the point size of this font.
14. getStyle()
This method gets the style of this font.
15. getName()
This method gets the logical name of this font.
16. getItalicAngle()
This method returns the angle in radians that the specified Font is italicized.
17. getNumGlyphs()
This method returns the number of glyphs in this Font.
18. getPSName()
This method returns the PostScript name of this Font.
19. getTransform()
This method returns the AffineTransform associated with this Font.
20. getAttributes()
This method returns an immutable Map of all the attributes of this Font.
21. getFontName()
This method returns the name of this font.
22. isBold()
This method returns true if this font has a bold style and false otherwise.
23. isItalic()
This method returns true if this font has an italic style and false otherwise.
24. isPlain()
This method returns true if this font has a plain style (i.e., neither bold nor italic) and false otherwise.
25. public Font deriveFont(Map<TextAttribute, ?> attributes)
This method returns a new Font object with the specified attributes.
26. public boolean canDisplay(char c)
This method returns true if this Font can display the specified character and false otherwise.
27. public boolean canDisplay(int codePoint)
This method returns true if this Font can display the specified Unicode code point and false otherwise.
28. deriveFont(Map<? extends AttributedCharacterIterator.Attribute, ?> attributes)
This method creates a new Font object based on this Font with the specified attributes.
29. deriveFont(int style)
This method creates a new Font object based on this Font with the specified style.
30. deriveFont(int style, float size)
This method creates a new Font object based on this Font with the specified style and size.
31. equals(Object obj)
This method compares this Font object to the specified Object.
32. hasLayoutAttributes()
This method returns a boolean value denoting whether or not this Font has any layout attributes.
33. hashCode()
This method gives a hash code value for the given Font object.
34. toString()
This method gives a String representation of this Font object.
Examples of Java Font
Example 1
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FontExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Font font = new Font("Verdana", Font.BOLD, 40);
g2d.setFont(font);
g2d.drawString("Hello, World!", 50, 100);
}
};
frame.add(panel);
frame.setVisible(true);
}
}
Output
Example 2
import java.awt.Font;
public class FontExample {
public static void main(String[] args) {
Font font = new Font("Arial", Font.BOLD, 18);
System.out.println("Font name: " + font.getFontName());
System.out.println("Font style: " + font.getStyle());
System.out.println("Font size: " + font.getSize());
}
}
Output
Example 3
import java.awt.*;
import javax.swing.*;
public class FontExample2 extends JPanel {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// Set font and size
Font font = new Font("Arial", Font.BOLD, 36);
g2.setFont(font);
// Set color
g2.setColor(Color.RED);
// Draw text
g2.drawString("Hello World!", 50, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Font Example");
frame.getContentPane().add(new FontExample2());
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output
Conclusion
In conclusion, Java Fonts are an essential aspect of Java programming, allowing developers to customize the look and feel of their applications. The Java Font class provides a wide range of methods for developers to work with, allowing them to create, manipulate, and customize font objects in their Java programs. With Java Fonts, developers can create visually appealing and user-friendly applications that stand out from the competition!
Recommended Articles
We hope that this EDUCBA information on “Java Font” was beneficial to you. You can view EDUCBA’s recommended articles for more information.