Core Java - [Java Font/FontMatrices Classes]

♠ Posted by Unknown in at 11:01

Java Font/FontMatrices Classes

You can set the font for the subjects you draw and use font matrics to obtain font size. Fonts and Font Matrices are encapsulated in two AWT classes: Font and FontMatrics.

To set a font, you need to create a Font object from the class Font class.
            Font myfont = new Font(name, style, size);

 Font myFont = new Font("TimesRoman", Font.BOLD, 16);
 Font myFont = new Font("TimesRoman", Font.BOLD + Font.ITALIC, 16);

YOu can use FontMatrices to computer the exact length and width of a string, which is helpful for measuring string size in order to display it in the right position.

Leading - This is the space amount between lines.
Ascent - This is the height of a character.
Descent - This is the distance from the baseline to the bottom of a descending character.
Height - This is the sum of leading, ascent, and descent.

Example:

import java.awt.*;
import java.awt.event.*;

public class FontExample extends Frame implements WindowListener
{
            public FontExample()
            {
                        addWindowListener(this);
            }
           
            public void paint(Graphics g)
            {
                        String message = "Welcome to Java";
                       
                        Font f = new Font("TimesRoman",Font.BOLD,16);
                        g.setFont(f);
                       
                        FontMetrics fm = g.getFontMetrics(f);
                       
                        int w = fm.stringWidth(message);
                        int h = fm.getAscent();
                        int x = (getSize().width - w)/2;
                        int y = (getSize().height - h)/2;
                        g.drawString(message, x, y);
            }
           
            public void windowClosed(WindowEvent e)
            {}
            public void windowDeiconified(WindowEvent e)
            {}
            public void windowIconified(WindowEvent e)
            {}
            public void windowActivated(WindowEvent e)
            {}
            public void windowDeactivated(WindowEvent e)
            {}
            public void windowOpened(WindowEvent e)
            {}
            public void windowClosing(WindowEvent e)
            {
                        dispose();
                        System.exit(0);
            }

            public static void main(String[] args)
            {
                        FontExample f = new FontExample();
                        f.setSize(300, 300);
                        f.setVisible(true);       
            }
}

0 comments:

Post a Comment