博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JPad 1.00(20081213)
阅读量:4176 次
发布时间:2019-05-26

本文共 26288 字,大约阅读时间需要 87 分钟。

  1. /**
  2.  * @author t0nsha(liaodunxia{at}gmail.com)
  3.  * @version 1.00(20081213)
  4.  */
  5. import javax.print.attribute.HashPrintRequestAttributeSet;
  6. import javax.print.attribute.PrintRequestAttributeSet;
  7. import javax.swing.ButtonGroup;
  8. import javax.swing.JButton;
  9. import javax.swing.JDialog;
  10. import javax.swing.JFileChooser;
  11. import javax.swing.JFrame;
  12. import javax.swing.JLabel;
  13. import javax.swing.JMenu;
  14. import javax.swing.JMenuBar;
  15. import javax.swing.JMenuItem;
  16. import javax.swing.JOptionPane;
  17. import javax.swing.JRadioButton;
  18. import javax.swing.JScrollPane;
  19. import javax.swing.JTextArea;
  20. import javax.swing.JTextField;
  21. import javax.swing.KeyStroke;
  22. import javax.swing.UIManager;
  23. import javax.swing.text.BadLocationException;
  24. import javax.swing.undo.UndoManager;
  25. import java.awt.BorderLayout;
  26. import java.awt.Checkbox;
  27. import java.awt.Container;
  28. import java.awt.Dimension;
  29. import java.awt.FlowLayout;
  30. import java.awt.Font;
  31. import java.awt.Frame;
  32. import java.awt.Graphics;
  33. import java.awt.Graphics2D;
  34. import java.awt.GraphicsEnvironment;
  35. import java.awt.GridLayout;
  36. import java.awt.List;
  37. import java.awt.Panel;
  38. import java.awt.Toolkit;
  39. import java.awt.event.ActionEvent;
  40. import java.awt.event.ActionListener;
  41. import java.awt.event.InputEvent;
  42. import java.awt.event.KeyEvent;
  43. import java.awt.event.WindowEvent;
  44. import java.awt.event.WindowListener;
  45. import java.awt.print.PageFormat;
  46. import java.awt.print.Printable;
  47. import java.awt.print.PrinterException;
  48. import java.awt.print.PrinterJob;
  49. import java.io.File;
  50. import java.io.FileNotFoundException;
  51. import java.io.FileReader;
  52. import java.io.FileWriter;
  53. import java.io.IOException;
  54. import java.util.Calendar;
  55. public class JPad {
  56.     JFrame frame = new JFrame();
  57.     JMenuBar menuBar = new JMenuBar();
  58.     // JTextPane textpane = new JTextPane();
  59.     JTextArea textArea = new JTextArea();
  60.     String filepath = "";
  61.     String filename = "Untitled";
  62.     boolean dirty = false;
  63.     String savedContent = "";
  64.     String jpad = " - JPad";
  65.     UndoManager undoManager = new UndoManager();
  66.     StatusBar statusBar = new StatusBar();
  67.     boolean showStatusBar = true;
  68.     class StatusBar extends JLabel {
  69.         /** Creates a new instance of StatusBar */
  70.         public StatusBar() {
  71.             super();
  72.             super.setPreferredSize(new Dimension(10016));
  73.             setMessage(Calendar.getInstance().getTime().toString());
  74.         }
  75.         public void setMessage(String message) {
  76.             setText(" " + message);
  77.         }
  78.     }
  79.     class Daemon extends Thread {
  80.         Daemon() {
  81.             setDaemon(true);
  82.             start();
  83.         }
  84.         public void run() {
  85.             while (true) {
  86.                 try {
  87.                     sleep(100);
  88.                 } catch (InterruptedException e) {
  89.                     throw new RuntimeException(e);
  90.                 }
  91.                 statusBar.setMessage(Calendar.getInstance().getTime()
  92.                         .toString());
  93.                 // if (savedContent != textArea.getText()) {
  94.                 if (!savedContent.equals(textArea.getText())) {
  95.                     frame.setTitle("*" + filename + jpad);
  96.                     dirty = true;
  97.                 } else {
  98.                     frame.setTitle(filename + jpad);
  99.                     dirty = false;
  100.                 }
  101.             }
  102.         }
  103.     }
  104.     public class PrintDialog implements Printable {
  105.         public int print(Graphics g, PageFormat pf, int page)
  106.                 throws PrinterException {
  107.             if (page > 0) { /* We have only one page, and 'page' is zero-based */
  108.                 return NO_SUCH_PAGE;
  109.             }
  110.             /*
  111.              * User (0,0) is typically outside the imageable area, so we must
  112.              * translate by the X and Y values in the PageFormat to avoid
  113.              * clipping
  114.              */
  115.             Graphics2D g2d = (Graphics2D) g;
  116.             g2d.translate(pf.getImageableX(), pf.getImageableY());
  117.             /* Now we perform our rendering */
  118.             g.drawString(textArea.getText(), 100100);
  119.             /* tell the caller that this page is part of the printed document */
  120.             return PAGE_EXISTS;
  121.         }
  122.     }
  123.     class BrowserControl {
  124.         /**
  125.          * Display a file in the system browser. If you want to display a file,
  126.          * you must include the absolute path name.
  127.          * 
  128.          * @param url
  129.          *            the file's url (the url must start with either "http://"
  130.          *            or "file://").
  131.          */
  132.         public void displayURL(String url) {
  133.             boolean windows = isWindowsPlatform();
  134.             String cmd = null;
  135.             try {
  136.                 if (windows) {
  137.                     // cmd = 'rundll32 url.dll,FileProtocolHandler http://...'
  138.                     cmd = WIN_PATH + "   " + WIN_FLAG + "   " + url;
  139.                     Process p = Runtime.getRuntime().exec(cmd);
  140.                 } else {
  141.                     // Under Unix, Netscape has to be running for the "-remote"
  142.                     // command to work. So, we try sending the command and
  143.                     // check for an exit value. If the exit command is 0,
  144.                     // it worked, otherwise we need to start the browser.
  145.                     // cmd = 'netscape -remote
  146.                     // openURL(http://www.javaworld.com)'
  147.                     cmd = UNIX_PATH + "   " + UNIX_FLAG + "(" + url + ")";
  148.                     Process p = Runtime.getRuntime().exec(cmd);
  149.                     try {
  150.                         // wait for exit code -- if it's 0, command worked,
  151.                         // otherwise we need to start the browser up.
  152.                         int exitCode = p.waitFor();
  153.                         if (exitCode != 0) {
  154.                             // Command failed, start up the browser
  155.                             // cmd = 'netscape http://www.javaworld.com'
  156.                             cmd = UNIX_PATH + "   " + url;
  157.                             p = Runtime.getRuntime().exec(cmd);
  158.                         }
  159.                     } catch (InterruptedException x) {
  160.                         System.err
  161.                                 .println("Error   bringing   up   browser,   cmd='"
  162.                                         + cmd + "'");
  163.                         System.err.println("Caught:   " + x);
  164.                     }
  165.                 }
  166.             } catch (IOException x) {
  167.                 // couldn't exec browser
  168.                 System.err.println("Could   not   invoke   browser,   command="
  169.                         + cmd);
  170.                 System.err.println("Caught:   " + x);
  171.             }
  172.         }
  173.         /**
  174.          * Try to determine whether this application is running under Windows or
  175.          * some other platform by examing the "os.name" property.
  176.          * 
  177.          * @return true if this application is running under a Windows OS
  178.          */
  179.         public boolean isWindowsPlatform() {
  180.             String os = System.getProperty("os.name");
  181.             if (os != null && os.startsWith(WIN_ID))
  182.                 return true;
  183.             else
  184.                 return false;
  185.         }
  186.         // Used to identify the windows platform.
  187.         private static final String WIN_ID = "Windows";
  188.         // The default system browser under windows.
  189.         private static final String WIN_PATH = "rundll32";
  190.         // The flag to display a url.
  191.         private static final String WIN_FLAG = "url.dll,FileProtocolHandler";
  192.         // The default browser under unix.
  193.         private static final String UNIX_PATH = "netscape";
  194.         // The flag to display a url.
  195.         private static final String UNIX_FLAG = "-remote   openURL";
  196.     }
  197.     class FontChooser extends JDialog {
  198.         // Results:
  199.         /** The font the user has chosen */
  200.         protected Font resultFont;
  201.         /** The resulting font name */
  202.         protected String resultName;
  203.         /** The resulting font size */
  204.         protected int resultSize;
  205.         /** The resulting boldness */
  206.         protected boolean isBold;
  207.         /** The resulting italicness */
  208.         protected boolean isItalic;
  209.         // Working fields
  210.         /** Display text */
  211.         protected String displayText = "AaBbCcYyZz";
  212.         /** The list of Fonts */
  213.         protected String fontList[];
  214.         /** The font name chooser */
  215.         protected List fontNameChoice;
  216.         /** The font size chooser */
  217.         protected List fontSizeChoice;
  218.         /** The bold and italic choosers */
  219.         Checkbox bold, italic;
  220.         /** The list of font sizes */
  221.         protected String fontSizes[] = { "8""10""11""12""14""16",
  222.                 "18""20""24""30""36""40""48""60""72" };
  223.         /** The index of the default size (e.g., 14 point == 4) */
  224.         protected static final int DEFAULT_SIZE = 4;
  225.         /**
  226.          * The display area. Use a JLabel as the AWT label doesn't always honor
  227.          * setFont() in a timely fashion :-)
  228.          */
  229.         protected JLabel previewArea;
  230.         /**
  231.          * Construct a FontChooser -- Sets title and gets array of fonts on the
  232.          * system. Builds a GUI to let the user choose one font at one size.
  233.          */
  234.         public FontChooser(Frame f) {
  235.             super(f, "Font Chooser"true);
  236.             Container cp = getContentPane();
  237.             Panel top = new Panel();
  238.             top.setLayout(new FlowLayout());
  239.             fontNameChoice = new List(8);
  240.             top.add(fontNameChoice);
  241.             Toolkit toolkit = Toolkit.getDefaultToolkit();
  242.             // For JDK 1.1: returns about 10 names (Serif, SansSerif, etc.)
  243.             // fontList = toolkit.getFontList();
  244.             // For JDK 1.2: a much longer list; most of the names that come
  245.             // with your OS (e.g., Arial), plus the Sun/Java ones (Lucida,
  246.             // Lucida Bright, Lucida Sans...)
  247.             fontList = GraphicsEnvironment.getLocalGraphicsEnvironment()
  248.                     .getAvailableFontFamilyNames();
  249.             for (int i = 0; i < fontList.length; i++)
  250.                 fontNameChoice.add(fontList[i]);
  251.             fontNameChoice.select(0);
  252.             fontSizeChoice = new List(8);
  253.             top.add(fontSizeChoice);
  254.             for (int i = 0; i < fontSizes.length; i++)
  255.                 fontSizeChoice.add(fontSizes[i]);
  256.             fontSizeChoice.select(DEFAULT_SIZE);
  257.             cp.add(top, BorderLayout.NORTH);
  258.             Panel attrs = new Panel();
  259.             top.add(attrs);
  260.             attrs.setLayout(new GridLayout(01));
  261.             attrs.add(bold = new Checkbox("Bold"false));
  262.             attrs.add(italic = new Checkbox("Italic"false));
  263.             previewArea = new JLabel(displayText, JLabel.CENTER);
  264.             previewArea.setSize(20050);
  265.             cp.add(previewArea, BorderLayout.CENTER);
  266.             Panel bot = new Panel();
  267.             JButton okButton = new JButton("Apply");
  268.             bot.add(okButton);
  269.             okButton.addActionListener(new ActionListener() {
  270.                 public void actionPerformed(ActionEvent e) {
  271.                     previewFont();
  272.                     dispose();
  273.                     setVisible(false);
  274.                 }
  275.             });
  276.             JButton pvButton = new JButton("Preview");
  277.             bot.add(pvButton);
  278.             pvButton.addActionListener(new ActionListener() {
  279.                 public void actionPerformed(ActionEvent e) {
  280.                     previewFont();
  281.                 }
  282.             });
  283.             JButton canButton = new JButton("Cancel");
  284.             bot.add(canButton);
  285.             canButton.addActionListener(new ActionListener() {
  286.                 public void actionPerformed(ActionEvent e) {
  287.                     // Set all values to null. Better: restore previous.
  288.                     resultFont = null;
  289.                     resultName = null;
  290.                     resultSize = 0;
  291.                     isBold = false;
  292.                     isItalic = false;
  293.                     dispose();
  294.                     setVisible(false);
  295.                 }
  296.             });
  297.             cp.add(bot, BorderLayout.SOUTH);
  298.             previewFont(); // ensure view is up to date!
  299.             pack();
  300.             setLocation(100100);
  301.         }
  302.         /**
  303.          * Called from the action handlers to get the font info, build a font,
  304.          * and set it.
  305.          */
  306.         protected void previewFont() {
  307.             resultName = fontNameChoice.getSelectedItem();
  308.             String resultSizeName = fontSizeChoice.getSelectedItem();
  309.             int resultSize = Integer.parseInt(resultSizeName);
  310.             isBold = bold.getState();
  311.             isItalic = italic.getState();
  312.             int attrs = Font.PLAIN;
  313.             if (isBold)
  314.                 attrs = Font.BOLD;
  315.             if (isItalic)
  316.                 attrs |= Font.ITALIC;
  317.             resultFont = new Font(resultName, attrs, resultSize);
  318.             // System.out.println("resultName = " + resultName + "; " +
  319.             // "resultFont = " + resultFont);
  320.             previewArea.setFont(resultFont);
  321.             pack(); // ensure Dialog is big enough.
  322.         }
  323.         /** Retrieve the selected font name. */
  324.         public String getSelectedName() {
  325.             return resultName;
  326.         }
  327.         /** Retrieve the selected size */
  328.         public int getSelectedSize() {
  329.             return resultSize;
  330.         }
  331.         /** Retrieve the selected font, or null */
  332.         public Font getSelectedFont() {
  333.             return resultFont;
  334.         }
  335.     }
  336.     class FindReplace extends JDialog {
  337.         JLabel labelFindWhat = new JLabel("Find what: ");
  338.         JLabel labelReplaceWith = new JLabel("Repalce with: ");
  339.         JTextField textFieldFind = new JTextField();
  340.         JTextField textFieldReplace = new JTextField();
  341.         JButton find = new JButton("Find Next");
  342.         JRadioButton forward = new JRadioButton("Forward");
  343.         JRadioButton backward = new JRadioButton("Backward");
  344.         GridLayout gridLayout = new GridLayout(43);
  345.         JButton cancel = new JButton("Cancel");
  346.         ButtonGroup buttonGroup = new ButtonGroup();
  347.         Checkbox caseSensitive = new Checkbox("Case sensitive");
  348.         JButton replace = new JButton("Replace");
  349.         int selectionStart = textArea.getCaretPosition();
  350.         int selectionEnd = textArea.getCaretPosition();
  351.         FindReplace(Frame owner, String title, boolean modal) {
  352.             super(owner, title, modal);
  353.             this.setSize(400120);
  354.             Container cp = this.getContentPane();
  355.             cp.setLayout(gridLayout);
  356.             buttonGroup.add(backward);
  357.             buttonGroup.add(forward);
  358.             cp.add(labelFindWhat);
  359.             cp.add(textFieldFind);
  360.             cp.add(find);
  361.             cp.add(labelReplaceWith);
  362.             cp.add(textFieldReplace);
  363.             cp.add(replace);
  364.             cp.add(backward);
  365.             cp.add(forward);
  366.             cp.add(cancel);
  367.             cp.add(caseSensitive);
  368.             pack();
  369.             forward.setSelected(true);
  370.             cancel.addActionListener(new ActionListener() {
  371.                 public void actionPerformed(ActionEvent ae) {
  372.                     FindReplace.this.setVisible(false);
  373.                 }
  374.             });
  375.             find.addActionListener(new ActionListener() {
  376.                 public void actionPerformed(ActionEvent ae) {
  377.                     int findLen = textFieldFind.getText().length();
  378.                     int textLen = textArea.getText().length();
  379.                     int selectionStart = textArea.getCaretPosition();
  380.                     int selectionEnd = textArea.getCaretPosition();
  381.                     System.out.println("selectionEnd = " + selectionEnd
  382.                             + ", selectionEnd = " + selectionEnd);
  383.                     if (caseSensitive.getState() == true) {
  384.                         if (forward.isSelected()) {
  385.                             while ((selectionStart += findLen) <= (textLen - findLen)) {
  386.                                 try {
  387.                                     if (textArea.getText(selectionStart,
  388.                                             findLen).equals(
  389.                                             textFieldFind.getText())) {
  390.                                         selectionEnd = selectionStart + findLen;
  391.                                         textArea.select(selectionStart,
  392.                                                 selectionEnd);
  393.                                         break;
  394.                                     }
  395.                                 } catch (BadLocationException e) {
  396.                                     // TODO Auto-generated catch block
  397.                                     e.printStackTrace();
  398.                                 }
  399.                             }
  400.                         } else if (backward.isSelected()) {
  401.                             while ((selectionEnd -= findLen) >= findLen) {
  402.                                 try {
  403.                                     selectionStart = selectionEnd - findLen;
  404.                                     if (textArea.getText(selectionStart,
  405.                                             findLen).equals(
  406.                                             textFieldFind.getText())) {
  407.                                         textArea.select(selectionStart,
  408.                                                 selectionEnd);
  409.                                         break;
  410.                                     }
  411.                                 } catch (BadLocationException e) {
  412.                                     // TODO Auto-generated catch block
  413.                                     e.printStackTrace();
  414.                                 }
  415.                             }
  416.                         }
  417.                     } else if (caseSensitive.getState() == false) {
  418.                         if (forward.isSelected()) {
  419.                             while ((selectionStart += findLen) <= (textLen - findLen)) {
  420.                                 try {
  421.                                     if (textArea.getText(selectionStart,
  422.                                             findLen).toLowerCase().equals(
  423.                                             textFieldFind.getText()
  424.                                                     .toLowerCase())) {
  425.                                         selectionEnd = selectionStart + findLen;
  426.                                         textArea.select(selectionStart,
  427.                                                 selectionEnd);
  428.                                         break;
  429.                                     }
  430.                                 } catch (BadLocationException e) {
  431.                                     // TODO Auto-generated catch block
  432.                                     e.printStackTrace();
  433.                                 }
  434.                             }
  435.                         } else if (backward.isSelected()) {
  436.                             while ((selectionEnd -= findLen) >= findLen) {
  437.                                 try {
  438.                                     selectionStart = selectionEnd - findLen;
  439.                                     if (textArea.getText(selectionStart,
  440.                                             findLen).toLowerCase().equals(
  441.                                             textFieldFind.getText()
  442.                                                     .toLowerCase())) {
  443.                                         textArea.select(selectionStart,
  444.                                                 selectionEnd);
  445.                                         break;
  446.                                     }
  447.                                 } catch (BadLocationException e) {
  448.                                     // TODO Auto-generated catch block
  449.                                     e.printStackTrace();
  450.                                 }
  451.                             }
  452.                         }
  453.                     }
  454.                     if ((selectionStart > (textArea.getText().length() - findLen))
  455.                             || (selectionEnd < findLen)) {
  456.                         JOptionPane.showMessageDialog(FindReplace.this,
  457.                                 "Can not find /"" + textFieldFind.getText()
  458.                                         + "/"");
  459.                     }
  460.                 }
  461.             });
  462.             replace.addActionListener(new ActionListener() {
  463.                 public void actionPerformed(ActionEvent ae) {
  464.                     textArea.replaceSelection(textFieldReplace.getText());
  465.                 }
  466.             });
  467.         }
  468.     }
  469.     boolean askSaved() {
  470.         boolean ret = false;
  471.         if (dirty) {
  472.             int option = JOptionPane.showConfirmDialog(frame,
  473.                     "Content has been changed, do you want to save?");
  474.             if (option == JOptionPane.YES_OPTION) {
  475.                 saveAs(false);
  476.                 ret = true;
  477.             } else if (option == JOptionPane.NO_OPTION) {
  478.                 ret = true;
  479.             }
  480.         } else {
  481.             ret = true;
  482.         }
  483.         return ret;
  484.     }
  485.     void saveAs(boolean isSaveAs) {
  486.         if (isSaveAs) {
  487.             JFileChooser chooser = new JFileChooser();
  488.             int returnVal = chooser.showSaveDialog(frame);
  489.             if (returnVal == JFileChooser.APPROVE_OPTION) {
  490.                 filename = chooser.getSelectedFile().getName();
  491.                 filepath = chooser.getSelectedFile().getPath();
  492.                 try {
  493.                     FileWriter writer = new FileWriter(filepath);
  494.                     writer.write(textArea.getText());
  495.                     writer.close();
  496.                     savedContent = textArea.getText();
  497.                 } catch (IOException e) {
  498.                     // TODO Auto-generated catch block
  499.                     e.printStackTrace();
  500.                 }
  501.             }
  502.         } else {
  503.             if (filepath.length() != 0) {
  504.                 try {
  505.                     FileWriter writer = new FileWriter(filepath);
  506.                     writer.write(textArea.getText());
  507.                     writer.close();
  508.                     savedContent = textArea.getText();
  509.                 } catch (IOException e) {
  510.                     // TODO Auto-generated catch block
  511.                     e.printStackTrace();
  512.                 }
  513.             } else {
  514.                 JFileChooser chooser = new JFileChooser();
  515.                 int returnVal = chooser.showSaveDialog(frame);
  516.                 if (returnVal == JFileChooser.APPROVE_OPTION) {
  517.                     filename = chooser.getSelectedFile().getName();
  518.                     filepath = chooser.getSelectedFile().getPath();
  519.                     try {
  520.                         FileWriter writer = new FileWriter(filepath);
  521.                         writer.write(textArea.getText());
  522.                         writer.close();
  523.                         savedContent = textArea.getText();
  524.                     } catch (IOException e) {
  525.                         // TODO Auto-generated catch block
  526.                         e.printStackTrace();
  527.                     }
  528.                 }
  529.             }
  530.         }
  531.         frame.setTitle(filename + jpad);
  532.     }
  533.     void open() {
  534.         JFileChooser chooser = new JFileChooser();
  535.         int returnVal = chooser.showOpenDialog(frame);
  536.         if (returnVal == JFileChooser.APPROVE_OPTION) {
  537.             filepath = chooser.getSelectedFile().getPath();
  538.             filename = chooser.getSelectedFile().getName();
  539.             try {
  540.                 int offset = 0;
  541.                 int length = (int) (new File(filepath)).length();
  542.                 char[] cbuf = new char[length];
  543.                 FileReader reader = new FileReader(filepath);
  544.                 while (reader.ready()) {
  545.                     reader.read(cbuf, offset, length);
  546.                 }
  547.                 reader.close();
  548.                 textArea.setText(new String(cbuf));
  549.                 savedContent = new String(cbuf);
  550.             } catch (FileNotFoundException e) {
  551.                 // TODO Auto-generated catch block
  552.                 e.printStackTrace();
  553.             } catch (IOException e) {
  554.                 // TODO Auto-generated catch block
  555.                 e.printStackTrace();
  556.             }
  557.         }
  558.         frame.setTitle(filename + jpad);
  559.     }
  560.     void jnew() {
  561.         savedContent = "";
  562.         textArea.setText("");
  563.         filename = "Untitled";
  564.         frame.setTitle(filename + jpad);
  565.     }
  566.     class FrameL implements WindowListener {
  567.         @Override
  568.         public void windowActivated(WindowEvent e) {
  569.             // TODO Auto-generated method stub
  570.         }
  571.         @Override
  572.         public void windowClosed(WindowEvent e) {
  573.             // TODO Auto-generated method stub
  574.         }
  575.         @Override
  576.         public void windowClosing(WindowEvent e) {
  577.             // TODO Auto-generated method stub
  578.             if (dirty) {
  579.                 if (askSaved()) {
  580.                     System.exit(0);
  581.                 }
  582.             } else {
  583.                 System.exit(0);
  584.             }
  585.         }
  586.         @Override
  587.         public void windowDeactivated(WindowEvent e) {
  588.             // TODO Auto-generated method stub
  589.         }
  590.         @Override
  591.         public void windowDeiconified(WindowEvent e) {
  592.             // TODO Auto-generated method stub
  593.         }
  594.         @Override
  595.         public void windowIconified(WindowEvent e) {
  596.             // TODO Auto-generated method stub
  597.         }
  598.         @Override
  599.         public void windowOpened(WindowEvent e) {
  600.             // TODO Auto-generated method stub
  601.         }
  602.     }
  603.     public JPad() {
  604.         new Daemon();
  605.         textArea.setText("");
  606.         frame.setTitle(filename + jpad);
  607.         frame.setSize(640480);
  608.         // add close handle
  609.         frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  610.         frame.addWindowListener(new FrameL());
  611.         // add menu fileMenu
  612.         JMenu fileMenu = new JMenu("File");
  613.         fileMenu.setMnemonic('F'); // make 'F' underlined.
  614.         menuBar.add(fileMenu);
  615.         // add menu item fileMenu --> new
  616.         JMenuItem fileNew = new JMenuItem("New"'N');
  617.         fileNew.setAccelerator(KeyStroke.getKeyStroke('N',
  618.                 InputEvent.CTRL_MASK, true));
  619.         fileNew.addActionListener(new ActionListener() {
  620.             public void actionPerformed(ActionEvent ae) {
  621.                 // JOptionPane.showMessageDialog(null, "fileMenu new");
  622.                 if (askSaved()) {
  623.                     jnew();
  624.                 }
  625.             }
  626.         });
  627.         fileMenu.add(fileNew);
  628.         // add menu item fileMenu --> open
  629.         JMenuItem fileOpen = new JMenuItem("Open..."'O');
  630.         fileOpen.setAccelerator(KeyStroke.getKeyStroke('O',
  631.                 InputEvent.CTRL_MASK, true));
  632.         fileOpen.addActionListener(new ActionListener() {
  633.             public void actionPerformed(ActionEvent ae) {
  634.                 // JOptionPane.showMessageDialog(null, "fileMenu open");
  635.                 if (askSaved()) {
  636.                     open();
  637.                 }
  638.             }
  639.         });
  640.         fileMenu.add(fileOpen);
  641.         // add menu item fileMenu --> save
  642.         JMenuItem fileSave = new JMenuItem("Save"'S');
  643.         fileSave.setAccelerator(KeyStroke.getKeyStroke('S',
  644.                 InputEvent.CTRL_MASK, true));
  645.         fileSave.addActionListener(new ActionListener() {
  646.             public void actionPerformed(ActionEvent ae) {
  647.                 // JOptionPane.showMessageDialog(null, "fileMenu save");
  648.                 saveAs(false);
  649.             }
  650.         });
  651.         fileMenu.add(fileSave);
  652.         // add menu item fileMenu --> save as
  653.         JMenuItem fileSaveAs = new JMenuItem("Save As..."'A');
  654.         fileSaveAs.addActionListener(new ActionListener() {
  655.             public void actionPerformed(ActionEvent ae) {
  656.                 // JOptionPane.showMessageDialog(null, "fileMenu save as");
  657.                 saveAs(true);
  658.             }
  659.         });
  660.         fileMenu.add(fileSaveAs);
  661.         // add menu item fileMenu --> separator
  662.         fileMenu.addSeparator();
  663.         // add menu item fileMenu --> print
  664.         JMenuItem filePrint = new JMenuItem("Print..."'P');
  665.         filePrint.setAccelerator(KeyStroke.getKeyStroke('P',
  666.                 InputEvent.CTRL_MASK, true));
  667.         filePrint.addActionListener(new ActionListener() {
  668.             public void actionPerformed(ActionEvent ae) {
  669.                 // JOptionPane.showMessageDialog(null, "fileMenu print");
  670.                 try {
  671.                     String cn = UIManager.getSystemLookAndFeelClassName();
  672.                     UIManager.setLookAndFeel(cn); // Use the native L&F
  673.                 } catch (Exception cnf) {
  674.                 }
  675.                 PrinterJob job = PrinterJob.getPrinterJob();
  676.                 PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
  677.                 PageFormat pf = job.pageDialog(aset);
  678.                 job.setPrintable(new PrintDialog(), pf);
  679.                 boolean ok = job.printDialog(aset);
  680.                 if (ok) {
  681.                     try {
  682.                         job.print(aset);
  683.                     } catch (PrinterException ex) {
  684.                         /* The job did not successfully complete */
  685.                     }
  686.                 }
  687.             }
  688.         });
  689.         fileMenu.add(filePrint);
  690.         // add menu item fileMenu --> separator
  691.         fileMenu.addSeparator();
  692.         // add menu item fileMenu --> exit
  693.         JMenuItem fileExit = new JMenuItem("Exit"'X');
  694.         fileExit.addActionListener(new ActionListener() {
  695.             public void actionPerformed(ActionEvent ae) {
  696.                 // JOptionPane.showMessageDialog(null, "fileMenu exit");
  697.                 if (askSaved()) {
  698.                     System.exit(0);
  699.                 }
  700.             }
  701.         });
  702.         fileMenu.add(fileExit);
  703.         // add menu edit
  704.         JMenu editMenu = new JMenu("Edit");
  705.         editMenu.setMnemonic('E');
  706.         menuBar.add(editMenu);
  707.         // add menu item edit --> undo typing
  708.         JMenuItem editUndoTyping = new JMenuItem("Undo Typing"'U');
  709.         editUndoTyping.setAccelerator(KeyStroke.getKeyStroke('Z',
  710.                 InputEvent.CTRL_MASK, true));
  711.         editUndoTyping.addActionListener(new ActionListener() {
  712.             public void actionPerformed(ActionEvent ae) {
  713.                 if (undoManager.canUndo()) {
  714.                     undoManager.undo();
  715.                 }
  716.             }
  717.         });
  718.         editMenu.add(editUndoTyping);
  719.         // add menu item edit --> separator
  720.         editMenu.addSeparator();
  721.         // add menu item edit --> cut
  722.         JMenuItem editCut = new JMenuItem("Cut"'T');
  723.         editCut.setAccelerator(KeyStroke.getKeyStroke('X',
  724.                 InputEvent.CTRL_MASK, true));
  725.         editCut.addActionListener(new ActionListener() {
  726.             public void actionPerformed(ActionEvent ae) {
  727.                 textArea.cut();
  728.             }
  729.         });
  730.         editMenu.add(editCut);
  731.         // add menu item edit --> copy
  732.         JMenuItem editCopy = new JMenuItem("Copy"'C');
  733.         editCopy.setAccelerator(KeyStroke.getKeyStroke('C',
  734.                 InputEvent.CTRL_MASK, true));
  735.         editCopy.addActionListener(new ActionListener() {
  736.             public void actionPerformed(ActionEvent ae) {
  737.                 textArea.copy();
  738.             }
  739.         });
  740.         editMenu.add(editCopy);
  741.         // add menu item edit --> paste
  742.         JMenuItem editPaste = new JMenuItem("Paste"'P');
  743.         editPaste.setAccelerator(KeyStroke.getKeyStroke('V',
  744.                 InputEvent.CTRL_MASK, true));
  745.         editPaste.addActionListener(new ActionListener() {
  746.             public void actionPerformed(ActionEvent ae) {
  747.                 textArea.paste();
  748.             }
  749.         });
  750.         editMenu.add(editPaste);
  751.         // add menu item edit --> delete
  752.         JMenuItem editDelete = new JMenuItem("Delete"'L');
  753.         editDelete
  754.                 .setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
  755.         editDelete.addActionListener(new ActionListener() {
  756.             public void actionPerformed(ActionEvent ae) {
  757.                 textArea.replaceSelection(null);
  758.             }
  759.         });
  760.         editMenu.add(editDelete);
  761.         // add menu item edit --> separator
  762.         editMenu.addSeparator();
  763.         // add menu item edit --> find
  764.         JMenuItem editFind = new JMenuItem("Find/Replace..."'F');
  765.         editFind.setAccelerator(KeyStroke.getKeyStroke('F',
  766.                 InputEvent.CTRL_MASK, true));
  767.         editFind.addActionListener(new ActionListener() {
  768.             public void actionPerformed(ActionEvent ae) {
  769.                 // JOptionPane.showMessageDialog(null, "edit find");
  770.                 FindReplace findReplace = new FindReplace(frame, "Find"false);
  771.                 findReplace.setVisible(true);
  772.             }
  773.         });
  774.         editMenu.add(editFind);
  775.         // add menu item edit --> go to
  776.         JMenuItem editGoto = new JMenuItem("Go To..."'G');
  777.         editGoto.setAccelerator(KeyStroke.getKeyStroke('G',
  778.                 InputEvent.CTRL_MASK, true));
  779.         editGoto.addActionListener(new ActionListener() {
  780.             public void actionPerformed(ActionEvent ae) {
  781.                 if (!textArea.getLineWrap()) {
  782.                     String s = JOptionPane.showInputDialog(null,
  783.                             "Line number: ""Go to the following row",
  784.                             JOptionPane.QUESTION_MESSAGE);
  785.                     // press Cancel will raise a NullPointerException
  786.                     if (s != null) {
  787.                         try {
  788.                             int i = Integer.parseInt(s);
  789.                             if (i > textArea.getLineCount()) {
  790.                                 JOptionPane.showMessageDialog(null,
  791.                                         "Row out of range.""JPad - Go To",
  792.                                         JOptionPane.NO_OPTION);
  793.                             } else {
  794.                                 textArea.setCaretPosition(textArea.getText()
  795.                                         .indexOf("/n", i - 1) + 1);
  796.                             }
  797.                         } catch (NumberFormatException nfe) {
  798.                             JOptionPane.showMessageDialog(null,
  799.                                     "Invalid Number!");
  800.                         }
  801.                     }
  802.                 } else {
  803.                     JOptionPane.showMessageDialog(null,
  804.                             "Please turn off auto wrap first!");
  805.                 }
  806.             }
  807.         });
  808.         editMenu.add(editGoto);
  809.         // add menu item separator
  810.         editMenu.addSeparator();
  811.         // add menu item edit --> select all
  812.         JMenuItem editSelectAll = new JMenuItem("Select All"'A');
  813.         editSelectAll.setAccelerator(KeyStroke.getKeyStroke('A',
  814.                 InputEvent.CTRL_MASK, true));
  815.         editSelectAll.addActionListener(new ActionListener() {
  816.             public void actionPerformed(ActionEvent ae) {
  817.                 textArea.selectAll();
  818.             }
  819.         });
  820.         editMenu.add(editSelectAll);
  821.         // add menu item edit --> time date
  822.         JMenuItem editTimeDate = new JMenuItem("Time/Date"'D');
  823.         editTimeDate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
  824.         editTimeDate.addActionListener(new ActionListener() {
  825.             public void actionPerformed(ActionEvent ae) {
  826.                 textArea.replaceSelection(Calendar.getInstance().getTime()
  827.                         .toString());
  828.             }
  829.         });
  830.         editMenu.add(editTimeDate);
  831.         // add menu option
  832.         JMenu optionMenu = new JMenu("Option");
  833.         optionMenu.setMnemonic('O');
  834.         menuBar.add(optionMenu);
  835.         // add menu item option --> auto wrap
  836.         JMenuItem optionAutoWrap = new JMenuItem("Auto Wrap"'W');
  837.         optionAutoWrap.addActionListener(new ActionListener() {
  838.             public void actionPerformed(ActionEvent ae) {
  839.                 textArea.setLineWrap(!textArea.getLineWrap());
  840.             }
  841.         });
  842.         optionMenu.add(optionAutoWrap);
  843.         // add menu item option --> auto wrap
  844.         JMenuItem optionFont = new JMenuItem("Font..."'F');
  845.         optionFont.addActionListener(new ActionListener() {
  846.             public void actionPerformed(ActionEvent ae) {
  847.                 // JOptionPane.showMessageDialog(null, "option font");
  848.                 FontChooser fc = new FontChooser(frame);
  849.                 fc.setVisible(true);
  850.                 Font f = fc.getSelectedFont();
  851.                 textArea.setFont(f);
  852.             }
  853.         });
  854.         optionMenu.add(optionFont);
  855.         // add menu view
  856.         JMenu viewMenu = new JMenu("View");
  857.         viewMenu.setMnemonic('V');
  858.         menuBar.add(viewMenu);
  859.         // add menu item view --> status bar
  860.         JMenuItem viewStatusBar = new JMenuItem("Status Bar"'S');
  861.         viewStatusBar.addActionListener(new ActionListener() {
  862.             public void actionPerformed(ActionEvent ae) {
  863.                 showStatusBar = !showStatusBar;
  864.                 statusBar.setVisible(showStatusBar);
  865.             }
  866.         });
  867.         viewMenu.add(viewStatusBar);
  868.         // add menu help
  869.         JMenu helpMenu = new JMenu("Help");
  870.         helpMenu.setMnemonic('H');
  871.         menuBar.add(helpMenu);
  872.         // add menu item help --> help contents
  873.         JMenuItem helpContents = new JMenuItem("Help Contents"'H');
  874.         helpContents.addActionListener(new ActionListener() {
  875.             public void actionPerformed(ActionEvent ae) {
  876.                 BrowserControl bc = new BrowserControl();
  877.                 bc.displayURL("http://blog.csdn.net/t0nsha");
  878.             }
  879.         });
  880.         helpMenu.add(helpContents);
  881.         // add menu item separator
  882.         helpMenu.addSeparator();
  883.         // add menu item help --> about jpad
  884.         JMenuItem helpAboutJPad = new JMenuItem("About JPad"'A');
  885.         helpAboutJPad.addActionListener(new ActionListener() {
  886.             public void actionPerformed(ActionEvent ae) {
  887.                 JOptionPane
  888.                         .showMessageDialog(
  889.                                 null,
  890.                                 "version 1.00(20081213)/n(c) t0nsha/nliaodunxia{at}gmail.com",
  891.                                 "About JPad", JOptionPane.INFORMATION_MESSAGE);
  892.             }
  893.         });
  894.         helpMenu.add(helpAboutJPad);
  895.         // add menu bar
  896.         frame.setJMenuBar(menuBar);
  897.         frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
  898.         // add text area
  899.         textArea.getDocument().addUndoableEditListener(undoManager);
  900.         frame.add(new JScrollPane(textArea));
  901.         frame.setVisible(true);
  902.     }
  903.     public static void main(String[] args) {
  904.         new JPad();
  905.     }
  906. }

 

jar文件匿名提取连接 http://pickup.mofile.com/1651850105553469

你可能感兴趣的文章
Hibernate中通过JPA entity graph的方式实现动态数据获取
查看>>
Hibernate中的数据获取方式及时机(fetching)
查看>>
Hibernate的二级缓存概述
查看>>
Hibernate二级缓存的全局配置
查看>>
Hibernate应用中通过JPA配置Entity缓存
查看>>
Hibernate中配置二级缓存的并发策略
查看>>
Hibernate的Entity cache(实体缓存)
查看>>
Hibernate中的Query cache(查询缓存)
查看>>
Hibernate的interceptors与events
查看>>
TestNG概述
查看>>
TestNG中测试方法的依赖关系详解
查看>>
TestNG中的运行时测试实例工厂详解
查看>>
TestNG测试的并发执行详解
查看>>
TestNG的监听器概述
查看>>
TestNG的IAnnotationTransformer监听器详解
查看>>
TestNG的IMethodInterceptor监听器详解
查看>>
TestNG的IHookable监听器详解
查看>>
TestNG的IConfigurable监听器详解
查看>>
TestNG的IConfigurationListener监听器详解
查看>>
TestNG的IExecutionListener监听器详解
查看>>