Section 5: Fonts and Colour

The following code shows how to set a widget's font, background and foreground colour.

import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
public class fontTest extends Applet
{ //Declare Labels
    JLabel smallSample;
    JLabel mediumSample;
    JLabel typeSample;
    JLabel titleSample;
    //Declare fonts 
    Font small = new Font ("Times New Roman", Font.PLAIN, 8);
    Font medium = new Font ("Times New Roman", Font.BOLD, 14);
    Font type = new Font ("Courier", Font.PLAIN, 12);
    Font title = new Font ("Arial", Font.ITALIC, 18);
    public void init ()
    { //Change applet's background colour
        setBackground (Color.orange);
        //construct & set smallSample's appearance
        smallSample = new JLabel ("This label is 8 pt font.");
        smallSample.setFont (small);
        smallSample.setBackground (Color.red);
        //construct & set mediumSample's appearance
        mediumSample = new JLabel ("This label is bold, 14 pt font.");
        mediumSample.setFont (medium);
        mediumSample.setForeground (Color.green);
        //construct & set typeSample's appearance
        typeSample = new JLabel ("This label is Courier font.");
        typeSample.setFont (type);
        typeSample.setForeground (Color.yellow);
        typeSample.setBackground (Color.black);
        //construct & set titleSample's appearance
        titleSample = new JLabel ("This label is Arial, italics, 18 pt font.");
        titleSample.setFont (title);
        //add Labels to applet
        add (smallSample);
        add (mediumSample);
        add (typeSample);
        add (titleSample);
    }
}