//    File:  TxtArea.java  -  How to use a TextArea, Menus, Accelerator Keys

import java.awt.*;
import java.awt.event.*;

public class TxtArea extends Frame {

    // Constructor -- set up the menu bar...
    public TxtArea() {
        super("TxtArea");
        add(textArea);
        setMenuBar(mBar);
        initFileMenu();
        textArea.addKeyListener(new KeyHandler());
    }

    // Shows how to allow Ctrl+E as an alternate "Accelerator Key"
    class KeyHandler extends KeyAdapter {
        public void keyTyped(KeyEvent e) {
            if (e.getModifiers() == CTRL_MODIFIER) {     // Ctrl key
                int key;
                switch (key = (int) e.getKeyChar()) {
                  case 'e' - 'a' + 1:                      // E = "exit"
                        e.consume();
                        exit();
                        break;
                }
            } 
        }
    }

    // Initialize the File menu
    private void initFileMenu() {
        ActionListener fh = new FileHandler();
        fileMenu = new Menu("File");
        mBar.add(fileMenu);
        fileMenu.addSeparator();
        exitItem = new MenuItem("Exit", new MenuShortcut('Q'));
        exitItem.addActionListener(fh);
        fileMenu.add(exitItem);
    }

    // Inner class containing the semantics of the File | Exit item
    private class FileHandler implements ActionListener {
        
        public void actionPerformed(ActionEvent e) {
            MenuItem m = (MenuItem) e.getSource();
            if (m == exitItem) {
                exit();
            }
        }

    }

    // Needs to be static because 'main' needs to call it...
    private static void exit() {
        System.exit(0);
    }

    // The main method...
    public static void main(String[] args) {
        ta = new TxtArea();
        ta.setBounds(150, 150, 275, 250);
        ta.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                exit();
            }
        });
        ta.setVisible(true);
    }

    private static final int CTRL_MODIFIER = 2;
    private static TxtArea ta;
    private MenuBar mBar = new MenuBar();
    private Menu fileMenu;
    private MenuItem exitItem;
    private final String sMsg = "\n    Please type in this text area...\n" +
                                "\n    You may use File | Exit" +
                                "\n    or Ctrl+q or Ctrl+e to exit...\n" +
                                "\n    You may resize this window...\n";
    private TextArea textArea = new TextArea(sMsg, 1, 1, TextArea.SCROLLBARS_VERTICAL_ONLY);
}
