Source of FontFixer.java


  2: import java.awt.Component;
  3: import java.awt.Container;
  4: import java.awt.Font;

  6: /**
  7:  * A utility class for changing font sizes in a swing GUI.
  8:  *
  9:  * @author Mark Young (A00000000)
 10:  */
 11: public class FontFixer {

 13:     /**
 14:      * Change the font size to a fixed value in a container and all its
 15:      * components.
 16:      *
 17:      * @param c the container to change the font size in
 18:      * @param size the size to change it to
 19:      */
 20:     public static void resizeFont(Component c, double size) {
 21:         Font myFont = c.getFont();
 22:         if (myFont != null) {
 23:             c.setFont(myFont.deriveFont((float) size));
 24:         }
 25:         if (c instanceof Container) {
 26:             for (Component comp : ((Container)c).getComponents()) {
 27:                 resizeFont(comp, size);
 28:             }
 29:         }
 30:     }

 32:     /**
 33:      * Change the font size by a scaling factor in a container and all its
 34:      * components. Numbers greater than 1 increase the size; smaller than one
 35:      * reduce the size.
 36:      *
 37:      * @param c the container to change the font size in
 38:      * @param factor the scaling factor to use
 39:      */
 40:     public static void scaleFont(Container c, double factor) {
 41:         Font oldFont = c.getFont();
 42:         float newSize = oldFont.getSize2D() * (float) factor;
 43:         Font newFont = c.getFont().deriveFont(newSize);
 44:         c.setFont(newFont);
 45:         for (Component comp : c.getComponents()) {
 46:             if (comp instanceof Container) {
 47:                 scaleFont((Container) comp, factor);
 48:             } else {
 49:                 comp.setFont(newFont);
 50:             }
 51:         }
 52:     }

 54: }