Academic Java    Java Tutorial  >  Graphics  >  font family

font family Example

Java font family EXAMPLE output Java font family EXAMPLE output This applet first shows how to access the font family names available to you.

It uses the first of these to render a string in a circle rendered with gradientPaint.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Font Family Example
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;

class FontFamilyExample extends JApplet {

   String family;

   @Override public void init() {
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      String[] fontNames = ge.getAvailableFontFamilyNames();
      for(int i=0; i<fontNames.length; ++i) {System.out.println(fontNames[i]);}
      family=fontNames[0];
   }

   @Override public void paint(Graphics g) {
      super.paint(g);

      Graphics2D g2 = (Graphics2D)g;
      Rectangle2D r = new Rectangle2D.Double(0, 0, 300, 300);
      g2.fill(r);

      GradientPaint gp = new GradientPaint(150,0,Color.red,
                  150,150,Color.yellow,true);
      g2.setPaint(gp);
      g2.fill(new Ellipse2D.Double(30,30,240,240));
      g2.setPaint(Color.black);

      Font font = new Font(family,Font.PLAIN,32);
      g2.setFont(font);
      g2.drawString("JAVA",115,160);

   }
}

11-13 The program uses the class GraphicsEnvironment and its method getLocalGraphicsEnvironment() to get the local GraphicsEnvironment. This has the method getAvailableFontFamilyNames() that returns a String[] containing all the font family names. We show some of these as output.

14 The first of these is used for drawing the "Java" string.