⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 notepad.java

📁 一个用JAVA编成的记事本程序。可实现跟电脑自带得记事本一样的功能
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*  */import java.awt.*;import java.awt.event.*;import java.beans.*;import java.io.*;import java.net.URL;import java.util.*;import javax.swing.text.*;import javax.swing.undo.*;import javax.swing.event.*;import javax.swing.*;/** * Sample application using the simple text editor component that * supports only one font. * * @author  Timothy Prinzing * @version 1.31 11/17/05  */class Notepad extends JPanel {    private static ResourceBundle resources;    private final static String EXIT_AFTER_PAINT = new String("-exit");    private static boolean exitAfterFirstPaint;    static {        try {            resources = ResourceBundle.getBundle("resources.Notepad",                                                  Locale.getDefault());        } catch (MissingResourceException mre) {            System.err.println("resources/Notepad.properties not found");            System.exit(1);        }    }    public void paintChildren(Graphics g) {        super.paintChildren(g);        if (exitAfterFirstPaint) {            System.exit(0);        }    }    Notepad() {	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 = Boolean.valueOf(vpFlag);	    port.setBackingStoreEnabled(bs.booleanValue());	} catch (MissingResourceException mre) {	    // just use the viewport default	}	menuItems = new Hashtable();	JPanel panel = new JPanel();	panel.setLayout(new BorderLayout());		panel.add("North",createToolbar());	panel.add("Center", scroller);	add("Center", panel);	add("South", createStatusbar());    }    public static void main(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!!!");        }        if (args.length > 0 && args[0].equals(EXIT_AFTER_PAINT)) {            exitAfterFirstPaint = true;        }        JFrame frame = new JFrame();        frame.setTitle(resources.getString("Title"));	frame.setBackground(Color.lightGray);	frame.getContentPane().setLayout(new BorderLayout());        Notepad notepad = new Notepad();	frame.getContentPane().add("Center", notepad);        frame.setJMenuBar(notepad.createMenubar());	frame.addWindowListener(new AppCloser());	frame.pack();	frame.setSize(500, 600);        frame.show();        } catch (Throwable t) {            System.out.println("uncaught exception: " + t);            t.printStackTrace();        }    }    /**     * 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.     */    public Action[] getActions() {	return TextAction.augmentList(editor.getActions(), defaultActions);    }    /**     * Create an editor to represent the given document.       */    protected JTextComponent createEditor() {	JTextComponent c = new JTextArea();	c.setDragEnabled(true);	c.setFont(new Font("monospaced", Font.PLAIN, 12));	return c;    }    /**      * Fetch the editor contained in this panel     */    protected JTextComponent getEditor() {	return editor;    }    /**     * To shutdown when run as an application.  This is a     * fairly lame implementation.   A more self-respecting     * implementation would at least check to see if a save     * was needed.     */    protected static final class AppCloser extends WindowAdapter {        public void windowClosing(WindowEvent e) {	    System.exit(0);	}    }    /**     * Find the hosting frame, for the file-chooser dialog.     */    protected Frame getFrame() {	for (Container p = getParent(); p != null; p = p.getParent()) {	    if (p instanceof Frame) {		return (Frame) p;	    }	}	return null;    }    /**     * 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     */    protected JMenuItem createMenuItem(String cmd) {	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;    }    /**     * 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.     */    protected JMenuItem getMenuItem(String cmd) {	return (JMenuItem) menuItems.get(cmd);    }    protected Action getAction(String cmd) {	return (Action) commands.get(cmd);    }    protected String getResourceString(String nm) {	String str;	try {	    str = resources.getString(nm);	} catch (MissingResourceException mre) {	    str = null;	}	return str;    }    protected URL getResource(String key) {	String name = getResourceString(key);	if (name != null) {	    URL url = this.getClass().getResource(name);	    return url;	}	return null;    }    protected Container getToolbar() {	return toolbar;    }    protected JMenuBar getMenubar() {	return menubar;    }    /**     * Create a status bar     */    protected Component createStatusbar() {	// need to do something reasonable here	status = new StatusBar();	return status;    }    /**     * Resets the undo manager.     */    protected void resetUndoManager() {	undo.discardAllEdits();	undoAction.update();	redoAction.update();    }    /**     * Create the toolbar.  By default this reads the      * resource file for the definition of the toolbar.     */    private Component createToolbar() {	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;    }    /**     * Hook through which every toolbar item is created.     */    protected Component createTool(String key) {	return createToolbarButton(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.     */    protected JButton createToolbarButton(String key) {	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;    }    /**     * Take the given string and chop it up into a series     * of strings on whitespace boundaries.  This is useful     * for trying to get an array of strings out of the     * resource file.     */    protected String[] tokenize(String input) {	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;    }    /**     * Create the menubar for the app.  By default this pulls the     * definition of the menu from the associated resource file.      */    protected JMenuBar createMenubar() {	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);	    }	}        this.menubar = mb;	return mb;    }    /**     * Create a menu for the app.  By default this pulls the     * definition of the menu from the associated resource file.     */    protected JMenu createMenu(String key) {	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;    }    // Yarked from JMenu, ideally this would be public.    protected PropertyChangeListener createActionChangeListener(JMenuItem b) {	return new ActionChangedListener(b);    }    // Yarked from JMenu, ideally this would be public.    private class ActionChangedListener implements PropertyChangeListener {        JMenuItem menuItem;                ActionChangedListener(JMenuItem mi) {            super();            this.menuItem = mi;        }        public void propertyChange(PropertyChangeEvent e) {            String propertyName = e.getPropertyName();            if (e.getPropertyName().equals(Action.NAME)) {                String text = (String) e.getNewValue();                menuItem.setText(text);            } else if (propertyName.equals("enabled")) {                Boolean enabledState = (Boolean) e.getNewValue();                menuItem.setEnabled(enabledState.booleanValue());            }        }    }    private JTextComponent editor;    private Hashtable commands;    private Hashtable menuItems;    private JMenuBar menubar;    private JToolBar toolbar;    private JComponent status;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -