FileDocCategorySizeDatePackage
Notepad.javaAPI DocSun JDK 1.4.2 Example20348Thu May 12 00:35:27 BST 2005None

Notepad

public class Notepad extends JPanel
Sample application using the simple text editor component that supports only one font.
author
Timothy Prinzing
version
1.21 01/23/03

Fields Summary
private static ResourceBundle
resources
private JTextComponent
editor
private Hashtable
commands
private Hashtable
menuItems
private JMenuBar
menubar
private JToolBar
toolbar
private JComponent
status
private JFrame
elementTreeFrame
protected ElementTreePanel
elementTreePanel
protected FileDialog
fileDialog
protected UndoableEditListener
undoHandler
Listener for the edits on the current document.
protected UndoManager
undo
UndoManager that we add edits to.
public static final String
imageSuffix
Suffix applied to the key used in resource file lookups for an image.
public static final String
labelSuffix
Suffix applied to the key used in resource file lookups for a label.
public static final String
actionSuffix
Suffix applied to the key used in resource file lookups for an action.
public static final String
tipSuffix
Suffix applied to the key used in resource file lookups for tooltip text.
public static final String
openAction
public static final String
newAction
public static final String
saveAction
public static final String
exitAction
public static final String
showElementTreeAction
private UndoAction
undoAction
private RedoAction
redoAction
private Action[]
defaultActions
Actions defined by the Notepad class
Constructors Summary
Notepad()

        try {
            resources = ResourceBundle.getBundle("resources.Notepad", 
                                                 Locale.getDefault());
        } catch (MissingResourceException mre) {
            System.err.println("resources/Notepad.properties not found");
            System.exit(1);
        }
    
	super(true);

	// Force SwingSet to come up in the Cross Platform L&F
	try {
	    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
	    // If you want the System L&F instead, comment out the above line and
	    // uncomment the following:
	    // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	} catch (Exception exc) {
	    System.err.println("Error loading L&F: " + exc);
	}

	setBorder(BorderFactory.createEtchedBorder());
	setLayout(new BorderLayout());

	// create the embedded JTextComponent
	editor = createEditor();
	// Add this as a listener for undoable edits.
	editor.getDocument().addUndoableEditListener(undoHandler);

	// install the command table
	commands = new Hashtable();
	Action[] actions = getActions();
	for (int i = 0; i < actions.length; i++) {
	    Action a = actions[i];
	    //commands.put(a.getText(Action.NAME), a);
	    commands.put(a.getValue(Action.NAME), a);
	}
	
	JScrollPane scroller = new JScrollPane();
	JViewport port = scroller.getViewport();
	port.add(editor);
	try {
	    String vpFlag = resources.getString("ViewportBackingStore");
	    Boolean bs = new Boolean(vpFlag);
	    port.setBackingStoreEnabled(bs.booleanValue());
	} catch (MissingResourceException mre) {
	    // just use the viewport default
	}

	menuItems = new Hashtable();
	menubar = createMenubar();
	add("North", menubar);
	JPanel panel = new JPanel();
	panel.setLayout(new BorderLayout());	
	panel.add("North",createToolbar());
	panel.add("Center", scroller);
	add("Center", panel);
	add("South", createStatusbar());
    
Methods Summary
protected java.beans.PropertyChangeListenercreateActionChangeListener(javax.swing.JMenuItem b)

	return new ActionChangedListener(b);
    
protected javax.swing.text.JTextComponentcreateEditor()
Create an editor to represent the given document.

	JTextComponent c = new JTextArea();
	c.setDragEnabled(true);
	c.setFont(new Font("monospaced", Font.PLAIN, 12));
	return c;
    
protected javax.swing.JMenucreateMenu(java.lang.String key)
Create a menu for the app. By default this pulls the definition of the menu from the associated resource file.

	String[] itemKeys = tokenize(getResourceString(key));
	JMenu menu = new JMenu(getResourceString(key + "Label"));
	for (int i = 0; i < itemKeys.length; i++) {
	    if (itemKeys[i].equals("-")) {
		menu.addSeparator();
	    } else {
		JMenuItem mi = createMenuItem(itemKeys[i]);
		menu.add(mi);
	    }
	}
	return menu;
    
protected javax.swing.JMenuItemcreateMenuItem(java.lang.String cmd)
This is the hook through which all menu items are created. It registers the result with the menuitem hashtable so that it can be fetched with getMenuItem().

see
#getMenuItem

	JMenuItem mi = new JMenuItem(getResourceString(cmd + labelSuffix));
        URL url = getResource(cmd + imageSuffix);
	if (url != null) {
	    mi.setHorizontalTextPosition(JButton.RIGHT);
	    mi.setIcon(new ImageIcon(url));
	}
	String astr = getResourceString(cmd + actionSuffix);
	if (astr == null) {
	    astr = cmd;
	}
	mi.setActionCommand(astr);
	Action a = getAction(astr);
	if (a != null) {
	    mi.addActionListener(a);
	    a.addPropertyChangeListener(createActionChangeListener(mi));
	    mi.setEnabled(a.isEnabled());
	} else {
	    mi.setEnabled(false);
	}
	menuItems.put(cmd, mi);
	return mi;
    
protected javax.swing.JMenuBarcreateMenubar()
Create the menubar for the app. By default this pulls the definition of the menu from the associated resource file.

	JMenuItem mi;
	JMenuBar mb = new JMenuBar();

	String[] menuKeys = tokenize(getResourceString("menubar"));
	for (int i = 0; i < menuKeys.length; i++) {
	    JMenu m = createMenu(menuKeys[i]);
	    if (m != null) {
		mb.add(m);
	    }
	}
	return mb;
    
protected java.awt.ComponentcreateStatusbar()
Create a status bar

	// need to do something reasonable here
	status = new StatusBar();
	return status;
    
protected java.awt.ComponentcreateTool(java.lang.String key)
Hook through which every toolbar item is created.

	return createToolbarButton(key);
    
private java.awt.ComponentcreateToolbar()
Create the toolbar. By default this reads the resource file for the definition of the toolbar.

	toolbar = new JToolBar();
	String[] toolKeys = tokenize(getResourceString("toolbar"));
	for (int i = 0; i < toolKeys.length; i++) {
	    if (toolKeys[i].equals("-")) {
		toolbar.add(Box.createHorizontalStrut(5));
	    } else {
		toolbar.add(createTool(toolKeys[i]));
	    }
	}
	toolbar.add(Box.createHorizontalGlue());
	return toolbar;
    
protected javax.swing.JButtoncreateToolbarButton(java.lang.String key)
Create a button to go inside of the toolbar. By default this will load an image resource. The image filename is relative to the classpath (including the '.' directory if its a part of the classpath), and may either be in a JAR file or a separate file.

param
key The key in the resource file to serve as the basis of lookups.

	URL url = getResource(key + imageSuffix);
        JButton b = new JButton(new ImageIcon(url)) {
            public float getAlignmentY() { return 0.5f; }
	};
        b.setRequestFocusEnabled(false);
        b.setMargin(new Insets(1,1,1,1));

	String astr = getResourceString(key + actionSuffix);
	if (astr == null) {
	    astr = key;
	}
	Action a = getAction(astr);
	if (a != null) {
	    b.setActionCommand(astr);
	    b.addActionListener(a);
	} else {
	    b.setEnabled(false);
	}

	String tip = getResourceString(key + tipSuffix);
	if (tip != null) {
	    b.setToolTipText(tip);
	}
 
        return b;
    
protected javax.swing.ActiongetAction(java.lang.String cmd)

	return (Action) commands.get(cmd);
    
public javax.swing.Action[]getActions()
Fetch the list of actions supported by this editor. It is implemented to return the list of actions supported by the embedded JTextComponent augmented with the actions defined locally.

	return TextAction.augmentList(editor.getActions(), defaultActions);
    
protected javax.swing.text.JTextComponentgetEditor()
Fetch the editor contained in this panel

	return editor;
    
protected java.awt.FramegetFrame()
Find the hosting frame, for the file-chooser dialog.

	for (Container p = getParent(); p != null; p = p.getParent()) {
	    if (p instanceof Frame) {
		return (Frame) p;
	    }
	}
	return null;
    
protected javax.swing.JMenuItemgetMenuItem(java.lang.String cmd)
Fetch the menu item that was created for the given command.

param
cmd Name of the action.
returns
item created for the given command or null if one wasn't created.

	return (JMenuItem) menuItems.get(cmd);
    
protected javax.swing.JMenuBargetMenubar()

	return menubar;
    
protected java.net.URLgetResource(java.lang.String key)

	String name = getResourceString(key);
	if (name != null) {
	    URL url = this.getClass().getResource(name);
	    return url;
	}
	return null;
    
protected java.lang.StringgetResourceString(java.lang.String nm)

	String str;
	try {
	    str = resources.getString(nm);
	} catch (MissingResourceException mre) {
	    str = null;
	}
	return str;
    
protected java.awt.ContainergetToolbar()

	return toolbar;
    
public static voidmain(java.lang.String[] args)

        try {
        String vers = System.getProperty("java.version");
        if (vers.compareTo("1.1.2") < 0) {
            System.out.println("!!!WARNING: Swing must be run with a " +
                               "1.1.2 or higher version VM!!!");
        }
        JFrame frame = new JFrame();
        frame.setTitle(resources.getString("Title"));
	frame.setBackground(Color.lightGray);
	frame.getContentPane().setLayout(new BorderLayout());
	frame.getContentPane().add("Center", new Notepad());
	frame.addWindowListener(new AppCloser());
	frame.pack();
	frame.setSize(500, 600);
        frame.show();
        } catch (Throwable t) {
            System.out.println("uncaught exception: " + t);
            t.printStackTrace();
        }
    
protected voidresetUndoManager()
Resets the undo manager.

	undo.discardAllEdits();
	undoAction.update();
	redoAction.update();
    
protected java.lang.String[]tokenize(java.lang.String input)
Take the given string and chop it up into a series of strings on whitespace boundries. This is useful for trying to get an array of strings out of the resource file.

	Vector v = new Vector();
	StringTokenizer t = new StringTokenizer(input);
	String cmd[];

	while (t.hasMoreTokens())
	    v.addElement(t.nextToken());
	cmd = new String[v.size()];
	for (int i = 0; i < cmd.length; i++)
	    cmd[i] = (String) v.elementAt(i);

	return cmd;