// Fig. 11.11: ScratchPad.java
// Incorporating menus into a subclass of Frame.
package com.deitel.jhtp2.ch11;
import java.awt.*;
import java.awt.event.*;

public class ScratchPad extends Frame
      implements ActionListener, ItemListener {
   private TextArea t;
   private String fontNames[] =
      { "TimesRoman", "Courier", "Helvetica" };
   private String colorNames[] =
      { "Black", "Red", "Green", "Blue" };
   private Color colorValues[] =
      { Color.black, Color.red, Color.green, Color.blue };

   private MenuBar bar;
   private Menu formatMenu, fontMenu, colorMenu;
   private MenuItem fonts[], colors[];
   private CheckboxMenuItem readOnly;

   public ScratchPad() 
   {
      super( "ScratchPad Application" );
      setSize( 300, 200 );

      t = new TextArea( "", 2, 20,
                        TextArea.SCROLLBARS_VERTICAL_ONLY);
      add( t, BorderLayout.CENTER );

      t.setFont( new Font( "TimesRoman", Font.PLAIN, 12 ) );
      t.setForeground( colorValues[ 0 ] );

      // create menubar
      bar = new MenuBar();

      // create the format menu
      formatMenu = new Menu( "Format" );

      // create font menu
      fontMenu = new Menu( "Font" );

      fonts = new MenuItem[ fontNames.length ];

      for ( int i = 0; i < fonts.length; i++ ) {
         fonts[ i ] = new MenuItem( fontNames[ i ] );
         fontMenu.add( fonts[ i ] );
         fonts[ i ].addActionListener( this );
      }

      formatMenu.add( fontMenu );
      formatMenu.addSeparator();

      // create color menu
      colorMenu = new Menu( "Color" );

      colors = new MenuItem[ colorNames.length ];

      for ( int i = 0; i < colors.length; i++ ) {
         colors[ i ] = new MenuItem( colorNames[ i ] );
         colorMenu.add( colors[ i ] );
         colors[ i ].addActionListener( this );
      }

      formatMenu.add( colorMenu );
      formatMenu.addSeparator();

      // create "read-only" menu item
      readOnly = new CheckboxMenuItem( "Read-Only" );
      readOnly.addItemListener( this );

      formatMenu.add( readOnly );

      // add menu to menu bar
      bar.add( formatMenu );

      // set the menubar for the frame
      setMenuBar( bar );
 
      setVisible( true );
   }

   // Handle font and color menu selections
   public void actionPerformed( ActionEvent e )
   {
      for ( int i = 0; i < fonts.length; i++ )
         if ( e.getSource() == fonts[ i ] ) {
            t.setFont( new Font( fonts[ i ].getLabel(),
               Font.PLAIN, 12 ) );
            break;
         }

      for ( int i = 0; i < colors.length; i++ )
         if ( e.getSource() == colors[ i ] ) {
            t.setForeground( colorValues[ i ] );
            break;
         }
   }

   // Handle "read-only" menu selections
   public void itemStateChanged( ItemEvent e )
   {
      t.setEditable( ! t.isEditable() );
   }
}
