Discussion of Activity 6.5 - Constructing a user interface to demonstrate fonts

Sample solution

Code for class FontDemo:

import java.awt.*;
import javax.swing.*;

public class FontDemo extends JFrame
{
   private JMenuBar menuBar;
   private JMenu helpMenu;
   private JMenuItem aboutItem;
   private JLabel fontChoiceLabel;
   private JComboBox fontChoices;
   private JLabel sizeChoiceLabel;
   private JTextField size;
   private JScrollPane scrollPane;
   private JLabel styleChoiceLabel;
   private JCheckBox bold;
   private JCheckBox italic;
   private JTextArea textBox;
   private JButton displayButton;
   private JPanel topPanel;
   private JPanel bottomPanel;

   public FontDemo()
   {
      setSize(400,240);
      setTitle("Font demo");
      setLocation(100,100);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container contentPane = getContentPane();
      contentPane.setLayout(new GridLayout(2,1));
      menuBar = new JMenuBar();
      helpMenu = new JMenu("Help");
      aboutItem = new JMenuItem("About");
      helpMenu.add(aboutItem);
      menuBar.add(helpMenu);
      setJMenuBar(menuBar);
      topPanel = new JPanel();
      bottomPanel = new JPanel();
      fontChoiceLabel = new JLabel("Font family");
      fontChoices = new JComboBox();
      fontChoices.addItem("SansSerif");
      fontChoices.addItem("Serif");
      fontChoices.addItem("Monospaced");
      topPanel.add(fontChoiceLabel);
      topPanel.add(fontChoices);
      sizeChoiceLabel = new JLabel("Size");
      topPanel.add(sizeChoiceLabel);
      size = new JTextField(3);
      size.setText("12");
      topPanel.add(size);
      styleChoiceLabel = new JLabel("Style");
      topPanel.add(styleChoiceLabel);
      bold = new JCheckBox("Bold");
      italic= new JCheckBox("Italic");
      topPanel.add(bold);
      topPanel.add(italic);
      displayButton = new JButton("Show font");
      topPanel.add(displayButton);

      textBox =
      new JTextArea("The cat sat on the mat.");
      scrollPane = new JScrollPane(textBox);
      bottomPanel.setLayout(new BorderLayout());
      bottomPanel.add(scrollPane,BorderLayout.CENTER);
      contentPane.add(topPanel);
      contentPane.add(bottomPanel);
   }
}

Code for class FontDemoTest:

public class FontDemoTest
{
   public static void main(String[] args)
   {
      FontDemo fd = new FontDemo();
      fd.setVisible(true);
   }
}