To display the font in center, the method paint() is defined. The Font class defines the font 'Monotype 'Corsiva'.
How to display the font in center
This section illustrates you how to display the font in center.
To display the font in center, the method paint() is defined. The Font class defines the font 'Monotype 'Corsiva'. The class FontRenderContext measures the text. The method g2d.getFont() gets the specified font. The method g2d.getFontRenderContext() get the rendering context of the Font. The method getStringBounds(st, fontRendContext) returns the bounds of the specified string.
A string is defined in the following way:
paint(g2d, "Java", 200, 75); paint(g2d, "is an", 200, 125); paint(g2d, "Object Oriented", 200, 175); paint(g2d, "Programming Language", 200, 225); |
Following code draws the String specified:
g2d.drawString(st, centerX - width / 2, baselineY); |
Here is the code of FontCenteredExample.java
import java.awt.*; import javax.swing.*; import java.awt.geom.Rectangle2D; import java.awt.font.FontRenderContext; public class FontCenteredExample extends JPanel { public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setFont(new Font("Monotype Corsiva", Font.PLAIN, 40)); paint(g2d, "Java", 200, 75); paint(g2d, "is an", 200, 125); paint(g2d, "Object Oriented", 200, 175); paint(g2d, "Programming Language", 200, 225); } protected void paint(Graphics2D g2d, String st, float point1 , float point2) { FontRenderContext fontRendContext = g2d.getFontRenderContext(); Rectangle2D rect = g2d.getFont().getStringBounds(st, fontRendContext); float width = (float) rect.getWidth(); g2d.drawString(st, point1 - width / 2, point2); } public static void main(String[] args) { JFrame frame = new JFrame("Font Centered Example"); frame.getContentPane().add(new FontCenteredExample()); frame.setSize(430, 300); frame.show(); } } |
Output will be displayed as: