Fonts.java


// Fig. 12.12: Fonts.java
// Using fonts.
import javax.swing.JFrame;
import java.awt.Font;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Fonts 
{
   // execute application
   public static void main( String[] args )
   {
      // create frame for FontJPanel
      JFrame frame = new JFrame( "Using fonts" );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      FontJPanel fontJPanel = new FontJPanel(); // create FontJPanel
      frame.add( fontJPanel ); // add fontJPanel to frame
      frame.setSize( 420, 150 ); // set frame size
      frame.setVisible( true ); // display frame
   } // end main
} // end class Fonts


class FontJPanel extends JPanel
{
   // display Strings in different fonts and colors
   public void paintComponent( Graphics g )
   {
      super.paintComponent( g ); // call superclass's paintComponent

      // set font to Serif (Times), bold, 12pt and draw a string 
      g.setFont( new Font( "Serif", Font.BOLD, 12 ) );
      g.drawString( "Serif 12 point bold.", 20, 30 );

      // set font to Monospaced (Courier), italic, 24pt and draw a string 
      g.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) );
      g.drawString( "Monospaced 24 point italic.", 20, 50 );

      // set font to SansSerif (Helvetica), plain, 14pt and draw a string 
      g.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) );
      g.drawString( "SansSerif 14 point plain.", 20, 70 );

      // set font to Serif (Times), bold/italic, 18pt and draw a string
      g.setColor( Color.RED );
      g.setFont( new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) );
      g.drawString( g.getFont().getName() + " " + g.getFont().getSize() +
         " point bold italic.", 20, 90 );
   } // end method paintComponent
} // end class FontJPanel


Results


Maintained by John Loomis, updated Tue May 27 12:37:41 2014