next next up down toc Memos schedule allInOne PDF PDF mail
all, section 14.13.

14.13.  Extreme Editor: ExtremeEditor

Src/13e/ExtremeEditor.java.minusSTART_STOP


//******************************************************************************
//
// File:    ExtremeEditor.java
//
//******************************************************************************


import javax.swing.JFrame;
import java.awt.Component;
import java.awt.Container;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputMethodListener;

import java.awt.BorderLayout;

import java.awt.Dimension;
import java.awt.Color;

import javax.swing.JScrollPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.JTextPane;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JColorChooser;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.AttributeSet;
import javax.swing.text.StyledDocument;
import javax.swing.JFileChooser;
import javax.swing.ImageIcon;
import javax.swing.Icon;
import javax.swing.JOptionPane;

import java.util.Hashtable;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;

import edu.rit.m2mi.M2MI;
import edu.rit.m2mi.SynthesisException;

/**
 * Class ExtremeEditor is the driver of the extreme editor.
 * Order of execution:
 * <UL>
 *      Initialize M2MI
 * <UL>
 *      paring the arguments --> split the frame in two panes or not
 * <UL>
 *      adding a HpStyledDocument to the pane 
 * </UL>
 * <P>
 * <B>M2MI Library Version October/20/2003</B>
 *
 * @author  Hans-Peter Bischof
 * @version October/20/2003
 */

public class ExtremeEditor extends JFrame {

/**
  * Initialize the M2MI layer.
  */
  static {
        try {
                M2MI.initialize(54321L);
        } catch (Throwable exc) {
                System.err.println ("ExtremeEditor: Uncaught exception");
                exc.printStackTrace (System.err);
        }

  }

  final protected static int WIDTH = 500;               // with of the frame
  final protected static int HEIGHT = 500;              // height of the frame
  static protected int HEIGHT_F = HEIGHT;               // heigt if split
  final protected static int MAX_READ = 512;            // # chars read and send at once
  protected JTextPane pane = null;                      // editor
  protected JTextPane ccPane = null;                    // carbon copy editor
  protected Hashtable aHashTable = new Hashtable();     // for colors
  protected JMenuBar menueBar = new JMenuBar();         // menue bar
  protected Color aColor = null;                        // actual color
  protected boolean split = false;                      // see parseArgs

/**
  * Creates a new ExtremeEditor.
  *
  * @param      text    Will be used to set the titlebar.
  *             
  */
  public ExtremeEditor(String text )    {
        super(text);
  }

/**
  * Returns the current used foreground color
  *
  * @return     the current used foreground color
  */
  public Color getColor()       {
        return aColor;
  }

/**
  * Allows to choose a new foreground color.
  */
  public void doColorCommand() {
        aColor = JColorChooser.showDialog(
                this, "Color Chooser", Color.cyan);
        if (aColor != null) {
                MutableAttributeSet attr = new SimpleAttributeSet();
                StyleConstants.setForeground(attr, aColor);
                pane.setCharacterAttributes(attr, false); 
            }
  }

/**
  * Loads a new file into the current buffer.
  * A modal dialog window will open if the file does not exist.
  */
  public void doLoadCommand() {
        JFileChooser chooser = new JFileChooser();
        int status = chooser.showOpenDialog(this);
        if (status == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
        
                        HpStyledDocument doc = (HpStyledDocument)pane.getStyledDocument();
                        doc.removeContent();
                        FileReader fileInputReader = new FileReader (file);
                        BufferedReader bufferedReader =
                                new BufferedReader(fileInputReader);
                        char buffer[] = new char[MAX_READ];
                        int len;
                        while ((len = bufferedReader.read(buffer, 0,
                                         buffer.length)) != -1) {
                                  doc.insertString(doc.getLength(),
                                      new String (buffer, 0, len), null);
                        }
              } catch (Exception exc) {
                        JOptionPane.showMessageDialog(null,
                                "Problems with Parsing the file", "alert",
                                JOptionPane.ERROR_MESSAGE); 
              }
        }
  }

/**
  * Saves the connent of the current buffer in a file.
  * A modal dialog window will open if the file does not exist.
  */
  public void doSaveCommand() {
        
        JFileChooser chooser = new JFileChooser();
        int status = chooser.showSaveDialog(this);
        if (status == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
        
                        HpStyledDocument doc = (HpStyledDocument)pane.getStyledDocument();
                        FileWriter fileOutputWriter = new FileWriter (file);
                        BufferedWriter bufferedWriter =
                                new BufferedWriter(fileOutputWriter);
                        int length = doc.getLength();
                        bufferedWriter.write( doc.getText(0, length) );
                        bufferedWriter.flush();
                        bufferedWriter.close();

              } catch (Exception exc) {
                        JOptionPane.showMessageDialog(null,
                                "Problems with Parsing the file", "alert",
                                JOptionPane.ERROR_MESSAGE); 
              }
        }
  }

/**
  * Creates the menue Bar
  *
  * @param      menueBar        the used menuBar
  */
  private void createFileMenue(JMenuBar menueBar)       {
        JMenu file = new JMenu ("File");
        JMenuItem item;
        file.add (item = new JMenuItem ("Load"));
        item.addActionListener (new ActionListener() {
                public void actionPerformed (ActionEvent e) {
                        doLoadCommand();
                }
        });
        file.add (item = new JMenuItem ("Save"));
        item.addActionListener (new ActionListener() {
                public void actionPerformed (ActionEvent e) {
                        doSaveCommand();
                }
        });
        file.addSeparator();
        file.add (item = new JMenuItem ("Close"));
        menueBar.add (file);
        item.addActionListener (new ActionListener() {
                public void actionPerformed (ActionEvent e) {
                        System.exit(0);
                }
        });
  }

  ActionListener aActionListener = 
        new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                        JMenuItem o = (JMenuItem)e.getSource();
                        MutableAttributeSet attr = new SimpleAttributeSet();
                        aColor = (Color)aHashTable.get(o.getText() );
                        if ( aColor != null )   {       // can not happen!
                                StyleConstants.setForeground(attr, aColor);
                                pane.setCharacterAttributes(attr, false); 
                        }
                }
  };


/**
  * Allows to pick a new foreground color.
  * This color will be used for all write activities.
  *
  * @param      label   the label
  * @param      aColor  printed in this forground color
  * @return     the current used foreground color
  */
  private JMenuItem addColorItem(String label, Color aColor)    {
        JMenuItem item = new JMenuItem (label);
        aHashTable.put(label, aColor);
        item.setIcon (new ColorSquare(aColor));
        item.addActionListener (aActionListener);
        return item;
  }

/**
  * Creates a new Color Menue
  *
  * @param      menueBar        under this menueBar
  */
  private void createColorMenue(JMenuBar menueBar)      {
        JMenuItem item;
        JMenu color = new JMenu("Color");

        color.add (addColorItem("Red", Color.red));
        color.add (addColorItem("Blue", Color.blue));
        color.add (addColorItem("Green", Color.green));

        color.add (item = new JMenuItem ("Custom Color"));
        item.addActionListener (new ActionListener() {
                public void actionPerformed (ActionEvent e) {
                doColorCommand();
                }
        });
        menueBar.add (color);
  }

/**
  * Creates a the the menueBar and the menues
  *
  */
  private void createMenues()   {

        JMenuBar menueBar = new JMenuBar();
        setJMenuBar (menueBar);
            
        createFileMenue(menueBar);
        createColorMenue(menueBar);
  }

  
/**
  * Creates all the visible elements
  * Two HpStyledDocument will appear in the frame if -split
  * is an argument. This is more for testing purpose.
  */
  private Component createFrameComponents() {
        Container aContainerPane = getContentPane();

        pane = new JTextPane( ( new HpStyledDocument(this)).export());

        JScrollPane sp = new JScrollPane (pane);
        if ( split )    {
                ccPane = new JTextPane( ( new HpStyledDocument(this)).export());
                HEIGHT_F = (int)( HEIGHT * 1.2);
                sp.setPreferredSize( new Dimension(WIDTH, HEIGHT / 2 ) );
                JScrollPane ccSp = new JScrollPane (ccPane);
                ccSp.setPreferredSize( new Dimension(WIDTH, HEIGHT / 2 ) );
                aContainerPane.add(ccSp, BorderLayout.SOUTH);
        } else
                sp.setPreferredSize( new Dimension(WIDTH, HEIGHT ) );
                
        aContainerPane.add(sp, BorderLayout.NORTH);

        return aContainerPane;
  }

  /**
    * Print the usage message and terminates.
    */
  private void printMessage()   {
        System.out.println("-h          ---->   help");
        System.out.println("[-split]    ---->   split the screen");
        System.exit(0);
  }
        
  /**
    * Parse the commandlind arguments and sets variables.
    * The program terminates, it the argumets include -h or
    * if one argument can not be recognized.
    */
  public void parseArgs(String args[]) {

        for (int i = 0; i < args.length; i ++) {
                if (args[i].equals("-h")) 
                        printMessage();
                else if (args[i].equals("-split"))      {
                        split = true;
                } else
                        printMessage();
        }
  }

/**
  * Main program
  */
  public static void main(String[] args) {

      ExtremeEditor app = new ExtremeEditor("ExtremeEditor");
      app.parseArgs(args);

      Component contents = app.createFrameComponents();
      app.createMenues();

      app.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
      });

      app.setSize(WIDTH, HEIGHT_F);
      app.setVisible(true);
  }
}

Source Code: Src/13e/ExtremeEditor.java


back next up down toc Memos schedule allInOne pdf PDF mail

Created by unroff, java2html & & hp-tools. © by csfac. All Rights Reserved (2010).
It is not allowed to print these pages on a CAST printer.
Last modified: 01/April/10 (17:16)