A Font class is used to set the screen fonts and it maps the characters of the language to their respective glyphs whereas a FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen.
Font
A Font class can be used to create an instance of a Font object to set the font for drawing text, label, text fields, buttons, etc and it can be specified by its name, style, and size.
The fonts have a family name, a logical name and a face-name
- family name: It is the general name of the font, such as Courier.
- logical name: It specifies a category of font, such as Monospaced.
- face name: It specifies a specific font, such as Courier Italic.
Example
import java.awt.*; import javax.swing.*; public class FontTest extends JPanel { public void paint(Graphics g) { g.setFont(new Font("TimesRoman", Font.BOLD, 15)); g.setColor(Color.blue); g.drawString("Welcome to Tutorials Point", 10, 20); } public static void main(String args[]) { JFrame test = new JFrame(); test.getContentPane().add(new FontTest()); test.setTitle("Font Test"); test.setSize(350, 275); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setLocationRelativeTo(null); test.setVisible(true); } }
Output
FontMetrics
The FontMetrics class is used to return the specific parameters for a particular Font object. An object of FontMetrics class is created using the getFontMetrics() method. The methods of FontMetrics class can provide access to the details of the implementation of a Font object. The methods bytesWidth(), charWidth(), charsWidth(), getWidth(), and stringWidth() are used to determine the width of a text object in pixels. These methods are essential for determining the horizontal position of text on the screen.
Example
import java.awt.*; import javax.swing.*; public class FontMetricsTest extends JPanel { public void paint(Graphics g) { String msg = "Tutorials Point"; Font f = new Font("Times New Roman",Font.BOLD|Font.ITALIC, 15); FontMetrics fm = getFontMetrics(f); g.setFont(f); int x =(getSize().width-fm.stringWidth(msg))/2; System.out.println("x= "+x); int y = getSize().height/2; System.out.println("y= "+y); g.drawString(msg, x, y); } public static void main(String args[]){ JFrame test = new JFrame(); test.getContentPane().add(new FontMetricsTest()); test.setTitle("FontMetrics Test"); test.setSize(350, 275); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setLocationRelativeTo(null); test.setVisible(true); } }