Notepad.java
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.*;
class Notepad extends JPanel { private static ResourceBundle resources; static {
try {
resources = ResourceBundle.getBundle("resources.Notepad",
Locale.getDefault());
} catch (MissingResourceException mre) {
System.err.println("resources/Notepad.properties not found");
System.exit(1);
}
} Notepad() {
super(true);
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception exc) {
System.err.println("Error loading L&F: " + exc);
} setBorder(BorderFactory.createEtchedBorder());
setLayout(new BorderLayout());
editor = createEditor();
editor.getDocument().addUndoableEditListener(undoHandler);
commands = new Hashtable();
Action[] actions = getActions();
for (int i = 0; i < actions.length; i++) {
Action a = actions[i];
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) {
} 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());
} 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!!!");
}
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.setVisible(true);
} catch (Throwable t) {
System.out.println("uncaught exception: " + t);
t.printStackTrace();
}
}
public Action[] getActions() {
return TextAction.augmentList(editor.getActions(), defaultActions);
}
protected JTextComponent createEditor() {
JTextComponent c = new JTextArea();
c.setDragEnabled(true);
c.setFont(new Font("monospaced", Font.PLAIN, 12));
return c;
}
protected JTextComponent getEditor() {
return editor;
}
protected static final class AppCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
protected Frame getFrame() {
for (Container p = getParent(); p != null; p = p.getParent()) {
if (p instanceof Frame) {
return (Frame) p;
}
}
return null;
}
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;
}
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;
}
protected Component createStatusbar() {
status = new StatusBar();
return status;
}
protected void resetUndoManager() {
undo.discardAllEdits();
undoAction.update();
redoAction.update();
}
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;
}
protected Component createTool(String key) {
return createToolbarButton(key);
}
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;
}
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;
}
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);
}
}
return mb;
}
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;
}
protected PropertyChangeListener createActionChangeListener(JMenuItem b) {
return new ActionChangedListener(b);
}
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;
private JFrame elementTreeFrame;
protected ElementTreePanel elementTreePanel;
protected FileDialog fileDialog;
protected UndoableEditListener undoHandler = new UndoHandler();
protected UndoManager undo = new UndoManager();
public static final String imageSuffix = "Image ";
public static final String labelSuffix = "Label ";
public static final String actionSuffix = "Action ";
public static final String tipSuffix = "Tooltip ";
public static final String openAction = "open ";
public static final String newAction = "new ";
public static final String saveAction = "save ";
public static final String exitAction = "exit ";
public static final String showElementTreeAction = "showElementTree ";
class UndoHandler implements UndoableEditListener {
public void undoableEditHappened(UndoableEditEvent e) {
undo.addEdit(e.getEdit());
undoAction.update();
redoAction.update();
}
}
class StatusBar extends JComponent {
public StatusBar() {
super();
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
}
public void paint(Graphics g) {
super.paint(g);
}
}
private UndoAction undoAction = new UndoAction();
private RedoAction redoAction = new RedoAction();
private Action[] defaultActions = {
new NewAction(),
new OpenAction(),
new ExitAction(),
new ShowElementTreeAction(),
undoAction,
redoAction
};
public UndoAction() {
super("Undo");
setEnabled(false);
} public void actionPerformed(ActionEvent e) {
try {
undo.undo();
} catch (CannotUndoException ex) {
System.out.println("Unable to undo: " + ex);
ex.printStackTrace();
}
update();
redoAction.update();
} protected void update() {
if(undo.canUndo()) {
setEnabled(true);
putValue(Action.NAME, undo.getUndoPresentationName());
}
else {
setEnabled(false);
putValue(Action.NAME, "Undo");
}
}
} class RedoAction extends AbstractAction {
public RedoAction() {
super("Redo");
setEnabled(false);
} public void actionPerformed(ActionEvent e) {
try {
undo.redo();
} catch (CannotRedoException ex) {
System.out.println("Unable to redo: " + ex);
ex.printStackTrace();
}
update();
undoAction.update();
} protected void update() {
if(undo.canRedo()) {
setEnabled(true);
putValue(Action.NAME, undo.getRedoPresentationName());
}
else {
setEnabled(false);
putValue(Action.NAME, "Redo");
}
}
} class OpenAction extends NewAction { OpenAction() {
super(openAction);
} public void actionPerformed(ActionEvent e) {
Frame frame = getFrame();
if (fileDialog == null) {
fileDialog = new FileDialog(frame);
}
fileDialog.setMode(FileDialog.LOAD);
fileDialog.setVisble(); String file = fileDialog.getFile();
if (file == null) {
return;
}
String directory = fileDialog.getDirectory();
File f = new File(directory, file);
if (f.exists()) {
Document oldDoc = getEditor().getDocument();
if(oldDoc != null)
oldDoc.removeUndoableEditListener(undoHandler);
if (elementTreePanel != null) {
elementTreePanel.setEditor(null);
}
getEditor().setDocument(new PlainDocument());
frame.setTitle(file);
Thread loader = new FileLoader(f, editor.getDocument());
loader.start();
}
}
}
class NewAction extends AbstractAction { NewAction() {
super(newAction);
} NewAction(String nm) {
super(nm);
} public void actionPerformed(ActionEvent e) {
Document oldDoc = getEditor().getDocument();
if(oldDoc != null)
oldDoc.removeUndoableEditListener(undoHandler);
getEditor().setDocument(new PlainDocument());
getEditor().getDocument().addUndoableEditListener(undoHandler);
resetUndoManager();
revalidate();
}
}
class ExitAction extends AbstractAction { ExitAction() {
super(exitAction);
} public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class ShowElementTreeAction extends AbstractAction { ShowElementTreeAction() {
super(showElementTreeAction);
} ShowElementTreeAction(String nm) {
super(nm);
} public void actionPerformed(ActionEvent e) {
if(elementTreeFrame == null) {
try {
String title = resources.getString
("ElementTreeFrameTitle");
elementTreeFrame = new JFrame(title);
} catch (MissingResourceException mre) {
elementTreeFrame = new JFrame();
} elementTreeFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent weeee) {
elementTreeFrame.setVisible(false);
}
});
Container fContentPane = elementTreeFrame.getContentPane(); fContentPane.setLayout(new BorderLayout());
elementTreePanel = new ElementTreePanel(getEditor());
fContentPane.add(elementTreePanel);
elementTreeFrame.pack();
}
elementTreeFrame.show();
}
}
class FileLoader extends Thread { FileLoader(File f, Document doc) {
setPriority(4);
this.f = f;
this.doc = doc;
} public void run() {
try {
status.removeAll();
JProgressBar progress = new JProgressBar();
progress.setMinimum(0);
progress.setMaximum((int) f.length());
status.add(progress);
status.revalidate();
Reader in = new FileReader(f);
char[] buff = new char[4096];
int nch;
while ((nch = in.read(buff, 0, buff.length)) != -1) {
doc.insertString(doc.getLength(), new String(buff, 0, nch), null);
progress.setValue(progress.getValue() + nch);
}
doc.addUndoableEditListener(undoHandler);
status.removeAll();
status.revalidate(); resetUndoManager();
}
catch (IOException e) {
System.err.println(e.toString());
}
catch (BadLocationException e) {
System.err.println(e.getMessage());
}
if (elementTreePanel != null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
elementTreePanel.setEditor(getEditor());
}
});
}
} Document doc;
File f;
}}
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.tree.*;
import javax.swing.undo.*;
import java.awt.*;
import java.beans.*;
import java.util.*;
public class ElementTreePanel extends JPanel implements CaretListener, DocumentListener, PropertyChangeListener, TreeSelectionListener {
protected JTree tree;
protected JTextComponent editor;
protected ElementTreeModel treeModel;
protected boolean updatingSelection; public ElementTreePanel(JTextComponent editor) {
this.editor = editor; Document document = editor.getDocument();
treeModel = new ElementTreeModel(document);
tree = new JTree(treeModel) {
public String convertValueToText(Object value, boolean selected,
boolean expanded, boolean leaf,
int row, boolean hasFocus) {
if(!(value instanceof Element))
return value.toString(); Element e = (Element)value;
AttributeSet as = e.getAttributes().copyAttributes();
String asString; if(as != null) {
StringBuffer retBuffer = new StringBuffer("[");
Enumeration names = as.getAttributeNames(); while(names.hasMoreElements()) {
Object nextName = names.nextElement(); if(nextName != StyleConstants.ResolveAttribute) {
retBuffer.append(" ");
retBuffer.append(nextName);
retBuffer.append("=");
retBuffer.append(as.getAttribute(nextName));
}
}
retBuffer.append(" ]");
asString = retBuffer.toString();
}
else
asString = "[ ]"; if(e.isLeaf())
return e.getName() + " [" + e.getStartOffset() +
", " + e.getEndOffset() +"] Attributes: " + asString;
return e.getName() + " [" + e.getStartOffset() +
", " + e.getEndOffset() + "] Attributes: " +
asString;
}
};
tree.addTreeSelectionListener(this);
tree.setDragEnabled(true);
tree.setRootVisible(false);
tree.setCellRenderer(new DefaultTreeCellRenderer() {
public Dimension getPreferredSize() {
Dimension retValue = super.getPreferredSize();
if(retValue != null)
retValue.width += 15;
return retValue;
}
});
document.addDocumentListener(this);
editor.addPropertyChangeListener(this);
editor.addCaretListener(this);
setLayout(new BorderLayout());
add(new JScrollPane(tree), BorderLayout.CENTER);
JLabel label = new JLabel("Elements that make up the current document", SwingConstants.CENTER); label.setFont(new Font("Dialog", Font.BOLD, 14));
add(label, BorderLayout.NORTH); setPreferredSize(new Dimension(400, 400));
}
public void setEditor(JTextComponent editor) {
if (this.editor == editor) {
return;
} if (this.editor != null) {
Document oldDoc = this.editor.getDocument(); oldDoc.removeDocumentListener(this);
this.editor.removePropertyChangeListener(this);
this.editor.removeCaretListener(this);
}
this.editor = editor;
if (editor == null) {
treeModel = null;
tree.setModel(null);
}
else {
Document newDoc = editor.getDocument(); newDoc.addDocumentListener(this);
editor.addPropertyChangeListener(this);
editor.addCaretListener(this);
treeModel = new ElementTreeModel(newDoc);
tree.setModel(treeModel);
}
}
public void propertyChange(PropertyChangeEvent e) {
if (e.getSource() == getEditor() &&
e.getPropertyName().equals("document")) {
JTextComponent editor = getEditor();
Document oldDoc = (Document)e.getOldValue();
Document newDoc = (Document)e.getNewValue();
oldDoc.removeDocumentListener(this);
newDoc.addDocumentListener(this);
treeModel = new ElementTreeModel(newDoc);
tree.setModel(treeModel);
}
}
public void insertUpdate(DocumentEvent e) {
updateTree(e);
}
public void removeUpdate(DocumentEvent e) {
updateTree(e);
}
public void changedUpdate(DocumentEvent e) {
updateTree(e);
}
public void caretUpdate(CaretEvent e) {
if(!updatingSelection) {
JTextComponent editor = getEditor();
int selBegin = Math.min(e.getDot(), e.getMark());
int end = Math.max(e.getDot(), e.getMark());
Vector paths = new Vector();
TreeModel model = getTreeModel();
Object root = model.getRoot();
int rootCount = model.getChildCount(root);
for(int counter = 0; counter < rootCount; counter++) {
int start = selBegin; while(start <= end) {
TreePath path = getPathForIndex(start, root,
(Element)model.getChild(root, counter));
Element charElement = (Element)path.
getLastPathComponent(); paths.addElement(path);
if(start >= charElement.getEndOffset())
start++;
else
start = charElement.getEndOffset();
}
}
int numPaths = paths.size(); if(numPaths > 0) {
TreePath[] pathArray = new TreePath[numPaths]; paths.copyInto(pathArray);
updatingSelection = true;
try {
getTree().setSelectionPaths(pathArray);
getTree().scrollPathToVisible(pathArray[0]);
}
finally {
updatingSelection = false;
}
}
}
}
public void valueChanged(TreeSelectionEvent e) {
JTree tree = getTree(); if(!updatingSelection && tree.getSelectionCount() == 1) {
TreePath selPath = tree.getSelectionPath();
Object lastPathComponent = selPath.getLastPathComponent(); if(!(lastPathComponent instanceof DefaultMutableTreeNode)) {
Element selElement = (Element)lastPathComponent; updatingSelection = true;
try {
getEditor().select(selElement.getStartOffset(),
selElement.getEndOffset());
}
finally {
updatingSelection = false;
}
}
}
}
return tree;
}
protected JTextComponent getEditor() {
return editor;
}
public DefaultTreeModel getTreeModel() {
return treeModel;
}
protected void updateTree(DocumentEvent event) {
updatingSelection = true;
try {
TreeModel model = getTreeModel();
Object root = model.getRoot(); for(int counter = model.getChildCount(root) - 1; counter >= 0;
counter--) {
updateTree(event, (Element)model.getChild(root, counter));
}
}
finally {
updatingSelection = false;
}
}
protected void updateTree(DocumentEvent event, Element element) {
DocumentEvent.ElementChange ec = event.getChange(element); if (ec != null) {
Element[] removed = ec.getChildrenRemoved();
Element[] added = ec.getChildrenAdded();
int startIndex = ec.getIndex();
if(removed != null && removed.length > 0) {
int[] indices = new int[removed.length]; for(int counter = 0; counter < removed.length; counter++) {
indices[counter] = startIndex + counter;
}
getTreeModel().nodesWereRemoved((TreeNode)element, indices,
removed);
}
if(added != null && added.length > 0) {
int[] indices = new int[added.length]; for(int counter = 0; counter < added.length; counter++) {
indices[counter] = startIndex + counter;
}
getTreeModel().nodesWereInserted((TreeNode)element, indices);
}
}
if(!element.isLeaf()) {
int startIndex = element.getElementIndex
(event.getOffset());
int elementCount = element.getElementCount();
int endIndex = Math.min(elementCount - 1,
element.getElementIndex
(event.getOffset() + event.getLength())); if(startIndex > 0 && startIndex < elementCount &&
element.getElement(startIndex).getStartOffset() ==
event.getOffset()) {
startIndex--;
}
if(startIndex != -1 && endIndex != -1) {
for(int counter = startIndex; counter <= endIndex; counter++) {
updateTree(event, element.getElement(counter));
}
}
}
else {
getTreeModel().nodeChanged((TreeNode)element);
}
}
protected TreePath getPathForIndex(int position, Object root,
Element rootElement) {
TreePath path = new TreePath(root);
Element child = rootElement.getElement
(rootElement.getElementIndex(position)); path = path.pathByAddingChild(rootElement);
path = path.pathByAddingChild(child);
while(!child.isLeaf()) {
child = child.getElement(child.getElementIndex(position));
path = path.pathByAddingChild(child);
}
return path;
}
public static class ElementTreeModel extends DefaultTreeModel {
protected Element[] rootElements; public ElementTreeModel(Document document) {
super(new DefaultMutableTreeNode("root"), false);
rootElements = document.getRootElements();
}
public Object getChild(Object parent, int index) {
if(parent == root)
return rootElements[index];
return super.getChild(parent, index);
}
public int getChildCount(Object parent) {
if(parent == root)
return rootElements.length;
return super.getChildCount(parent);
}
public boolean isLeaf(Object node) {
if(node == root)
return false;
return super.isLeaf(node);
}
public int getIndexOfChild(Object parent, Object child) {
if(parent == root) {
for(int counter = rootElements.length - 1; counter >= 0;
counter--) {
if(rootElements[counter] == child)
return counter;
}
return -1;
}
return super.getIndexOfChild(parent, child);
}
public void nodeChanged(TreeNode node) {
if(listenerList != null && node != null) {
TreeNode parent = node.getParent(); if(parent == null && node != root) {
parent = root;
}
if(parent != null) {
int anIndex = getIndexOfChild(parent, node); if(anIndex != -1) {
int[] cIndexs = new int[1]; cIndexs[0] = anIndex;
nodesChanged(parent, cIndexs);
}
}
}
}
protected TreeNode[] getPathToRoot(TreeNode aNode, int depth) {
TreeNode[] retNodes;
if(aNode == null) {
if(depth == 0)
return null;
else
retNodes = new TreeNode[depth];
}
else {
depth++;
if(aNode == root)
retNodes = new TreeNode[depth];
else {
TreeNode parent = aNode.getParent(); if(parent == null)
parent = root;
retNodes = getPathToRoot(parent, depth);
}
retNodes[retNodes.length - depth] = aNode;
}
return retNodes;
}
}
}
貌似对象该用.equals()吧
但是我又不知道用哪个替换 啊
能不能帮帮我啊 哪位高手啊
port.setBackingStoreEnabled(bs.booleanValue());
里的 setBackingStoreEnabled 过时了
能不能告诉我该用什么代替
String vpFlag = resources.getString("ViewportBackingStore");
Boolean bs = new Boolean(vpFlag);
port.setBackingStoreEnabled(bs.booleanValue());
} catch (MissingResourceException mre) {}把这几句直接去掉就行了,不会对功能有什么影响的。