java 记事本代码

来源:互联网 发布:乐视起诉b站2017 知乎 编辑:程序博客网 时间:2024/04/30 02:58
package NotePad;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.undo.UndoManager;
/**
 * @author zichen
 * @version 1.0
 * @since 1.0
 * @link http://bbs.korui.com
 */
public class NotePad {
    private JFrame frame;
    private JTextArea textArea;
    private JMenuBar menuBar;
    private JMenu file,edit,format,search,tool,help;
    private JMenuItem create,open,save,saveAs,pageSet,print,exit;
    private JMenuItem undo,redo,cut,copy,paste,delete,selectAll,dateTime;
    private JMenuItem font,color;
    private JMenuItem find,replace;
    private JMenuItem fileCount,screen;
    private JMenuItem helps,about;
    private JMenuItem MenuMouseCut,MenuMouseCopy,MenuMousePaste;
    private JCheckBoxMenuItem autoLine;
    private JToolBar toolbar;
    //private JComponent status;
    private JPanel panel;
    private JLabel statBar1,statBar2,statBar3,statBar4;
    private JPopupMenu popupMenu;
    private UndoManager undoListener;//"撤销"的监听器
    //other properties
    private File currentFile ;//当前文件
    private Boolean autoLineWrap=true;//记录是否自动换行
    private boolean bsaved = false;   //是否保存
    private boolean bchanged = false; //是否修改
    private String fileName = "未命名";//文件名
    private int mark=0;
    private String user;//当前用户
   
    public NotePad(){
        frame = new JFrame();
        frame.setTitle("未命名");
        frame.setLayout(new BorderLayout());
        frame.setFont(new Font("宋体",Font.PLAIN,14));//设置默认字体样式字号
        //set input textArea 设置编辑区
        textArea = new JTextArea();
        textArea.setText("");
        textArea.setLineWrap(autoLineWrap);//设置自动换行
        JScrollPane jsp = new JScrollPane(textArea);//set Scroll
        frame.add(jsp,BorderLayout.CENTER);
        initGUI();//初始化菜单
        //define toolbar 设置工具条
        toolbar = new JToolBar();
        //set status bar 设置状态条
        panel = new JPanel();
        panel.setLayout(new GridLayout(1,4));
        statBar1 = new JLabel();
        statBar2 = new JLabel();
        statBar3 = new JLabel();
        statBar4 = new JLabel();
        panel.add(statBar1);
        panel.add(statBar2);
        panel.add(statBar3);
        panel.add(statBar4);
        frame.add(panel,BorderLayout.SOUTH);
       
        statBar1.setText("status bar");
        String system = System.getProperty("os.name");
        String[] str=system.split(" ");
        if(str[0].equals("Windows")){
            user=System.getenv("USERNAME");//用于Windows系统
        }else{
            user=System.getenv("USER");//用于Linux系统
        }
        statBar2.setText("当前用户:"+user);
        //define popmenu 定义弹出菜单
        popupMenu = new JPopupMenu();
        MenuMouseCut = new JMenuItem("剪切");
        MenuMouseCopy = new JMenuItem("复制");
        MenuMousePaste = new JMenuItem("粘贴");
        popupMenu.add(MenuMouseCut);
        popupMenu.add(MenuMouseCopy);
        popupMenu.add(MenuMousePaste);
        //
        undoListener = new UndoManager();
        addEventHandler();//调用事件监听方法
        new refreshTime(statBar4).start();
    }

    public void initGUI(){
        //菜单
        menuBar = new JMenuBar();
        file = new JMenu("文件");
        file.setMnemonic('F');
        edit = new JMenu("编辑");
        format = new JMenu("格式");
        search = new JMenu("搜索");
        tool = new JMenu("工具");
        help = new JMenu("帮助");
        //文件菜单项
        create = new JMenuItem("新建",KeyEvent.VK_N);
        open = new JMenuItem("打开...",KeyEvent.VK_O);
        save = new JMenuItem("保存");
        save.setMnemonic('S');
        saveAs = new JMenuItem("另存为...");
        pageSet = new JMenuItem("页面设置...");
        print = new JMenuItem("打印");
        exit = new JMenuItem("退出");
        //编辑菜单项
        undo = new JMenuItem("撤消");
        redo = new JMenuItem("重做");
        cut = new JMenuItem("剪切");
        copy = new JMenuItem("复制");
        paste = new JMenuItem("粘贴");
        delete = new JMenuItem("删除");
        selectAll = new JMenuItem("全部选中");
        dateTime = new JMenuItem("日期/时间");
        //格式菜单项
        autoLine = new JCheckBoxMenuItem("自动换行");
        font = new JMenuItem("字体...");
        color = new JMenuItem("颜色...");
        //搜索菜单项
        find = new JMenuItem("查找...");
        replace = new JMenuItem("替换...");
        //工具菜单项
        fileCount = new JMenuItem("文件统计");
        screen = new JMenuItem("屏幕截图");
        //帮助菜单项
        helps = new JMenuItem("帮助");
        about = new JMenuItem("关于");
        //
        file.add(create);
        file.add(open);
        file.addSeparator();
        file.add(save);
        file.add(saveAs);
        file.addSeparator();
        file.add(pageSet);
        file.add(print);
        file.addSeparator();
        file.add(exit);
        edit.add(undo);
        edit.add(redo);
        edit.addSeparator();
        edit.add(cut);
        edit.add(copy);
        edit.add(paste);
        edit.add(delete);
        edit.addSeparator();
        edit.add(selectAll);
        edit.add(dateTime);   
        format.add(autoLine);
        format.add(font);
        format.add(color);
        search.add(find);
        search.add(replace);
        tool.add(fileCount);
        tool.add(screen);
        help.add(helps);
        help.add(about);
        menuBar.add(file);
        menuBar.add(edit);
        menuBar.add(format);
        menuBar.add(search);
        menuBar.add(tool);
        menuBar.add(help);
        //设置菜单条
        frame.setJMenuBar(menuBar);
    }
   
    private void addEventHandler(){
        //撤销的监听
        textArea.getDocument().addUndoableEditListener(undoListener);
        textArea.getDocument().addDocumentListener(new DocumentListener()
        {
            public void changedUpdate(DocumentEvent e) { bchanged=true;}
            public void insertUpdate(DocumentEvent e)    { bchanged=true;}
            public void removeUpdate(DocumentEvent e) { bchanged=true;}
        }
        );
        create.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){fileNew();}}
        );
        open.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){fileOpen();} }
        );
        save.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){fileSave();} }
        );
        saveAs.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){fileSaveTo();} }
        );
        pageSet.addActionListener(new ActionListener()
        {    public void actionPerformed(ActionEvent e){    pageSet();}}
        );   
        print.addActionListener(new ActionListener()
        {    public void actionPerformed(ActionEvent e){    print();}}
        );   
        exit.addActionListener(new ActionListener() //退出菜单的监听器
        {    public void actionPerformed(ActionEvent e){    fileExit();}}
        );   
        undo.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e)
            {
                if(undoListener.canUndo()){undoListener.undo();}//可撤销则撤销
            }
        });
        redo.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e)
            {
                if(undoListener.canRedo()){undoListener.redo();}//可重复
            }
        });
        cut.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){textArea.cut();}}
        );
        copy.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){textArea.copy();}}
        );
        paste.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){textArea.paste();}}
        );
        delete.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){textArea.replaceSelection("");}}
        );
        selectAll.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){
            textArea.setSelectionStart(0);
            textArea.setSelectionEnd(textArea.getText().length());
        }
        });
        dateTime.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){dateTime();}}
        );
        autoLine.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if(autoLineWrap){
                    textArea.setLineWrap(false);
                    autoLineWrap=false;
                }else{
                    textArea.setLineWrap(true);
                    autoLineWrap=true;
                }
            }
        }
        );
        font.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){new font(textArea);}}
        );
        color.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){setColor();}}
        );
        fileCount.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){fileCount();}}
        );
        screen.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                JFileChooser jc = new JFileChooser();
                int rVal=jc.showSaveDialog(frame);
                if(rVal==JFileChooser.APPROVE_OPTION){
                    File file = jc.getSelectedFile();
                    if(file==null) return;
             Camera cam= new Camera(file.toString(), "png");
             cam.snapShot();
                }
            }
        });
        find.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){fileFind();}
        });
        replace.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){fileReplace();}
        });
        about.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){about();}
        });
        textArea.addMouseMotionListener(new MouseMotionAdapter(){
            public void mouseMoved(MouseEvent e) {
                statBar3.setText("X: "+e.getX()+"  Y: "+e.getY());
            }
        }) ;
        textArea.addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e){checkForTriggerEvent(e);}
            public void mouseReleased(MouseEvent e){checkForTriggerEvent(e);}
            private void checkForTriggerEvent(MouseEvent e){
                if(e.isPopupTrigger())
                    popupMenu.show(e.getComponent(),e.getX(),e.getY());
            }
        });
        MenuMouseCut.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){textArea.cut();}}
        );
        MenuMouseCopy.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){textArea.copy();}}
        );
        MenuMousePaste.addActionListener(new ActionListener()
        {public void actionPerformed(ActionEvent e){textArea.paste();}}
        );
    }
    //
    private void fileNew(){
        if(bchanged){//文件内容发生改变
            int i=JOptionPane.showConfirmDialog(frame,"文档已经修改,是否保存?");
            if(i==JOptionPane.YES_OPTION) fileSave();
            if(i==JOptionPane.CANCEL_OPTION) return;
        }
        textArea.setText("");
        frame.setTitle("未命名");
        statBar1.setText("当前文件: ");
        bchanged=false;
    }
    private void fileOpen(){
        textArea.setText("");
        JFileChooser fileChooser=new JFileChooser();
        fileChooser.showOpenDialog(frame);
        File file=fileChooser.getSelectedFile();
        if(file==null) return;
        fileName = file.getName();//获得文件名
        frame.setTitle(file.getAbsolutePath());
        FileInputStream fis=null;
        BufferedReader br=null;
        try {
            fis=new FileInputStream(file);
            br=new BufferedReader(new InputStreamReader(fis));
            String str=null;
            while((str=br.readLine())!=null){
                textArea.append(str+"/n");
            }
            currentFile=file;
        } catch (IOException e1) {
            JOptionPane.showMessageDialog(frame,"文件不存在或已被损坏");
        }finally{
            if(br!=null)try{br.close();}catch(IOException e){}
            if(fis!=null)try{fis.close();}catch(IOException e){}
        }
        bchanged=false;
        statBar1.setText("当前文件: "+ fileName);
    }
    private void fileSave(){
        if(currentFile==null||bchanged){
            JFileChooser fileChooser=new JFileChooser();
            int op=fileChooser.showSaveDialog(frame);
            if(op==JFileChooser.CANCEL_OPTION){
                return;
            }
            File file=fileChooser.getSelectedFile();
            if(save(file)){
                currentFile=file;
            }
        }else{
            save(currentFile);
            return;
        }
    }
    private void fileSaveTo(){
        JFileChooser fileChooser=new JFileChooser();
        int op=fileChooser.showSaveDialog(frame);
        if(op==JFileChooser.CANCEL_OPTION){
            return ;
        }
        File file=fileChooser.getSelectedFile();
        if(save(file)){
            currentFile=file;
        }
    }
    private boolean save(File file){
        if( file.exists() && !file.equals(currentFile)){//如果已经存在同名文件
            //询问是否覆盖?
            int op=JOptionPane.showConfirmDialog(frame,"该文件已存在,是否覆盖?","覆盖文件",JOptionPane.YES_NO_CANCEL_OPTION);
            switch(op){
            case JOptionPane.YES_OPTION:break;
            case JOptionPane.NO_OPTION:return false;
            case JOptionPane.CANCEL_OPTION:return false;
            }
        }
        FileOutputStream fos=null;
        PrintWriter pw=null;
        try {
            fos=new FileOutputStream(file);
            pw=new PrintWriter(fos);
            pw.print(textArea.getText());
            pw.flush();
        } catch (IOException e1) {
            JOptionPane.showMessageDialog(frame,"保存文件出错,可能已写保护或文件正在使用!");
            return false;
        }finally{
            if(fos!=null)try{fos.close();}catch(IOException e){}
        }
        frame.setTitle(file.getAbsolutePath());
        fileName = file.getName();
        statBar1.setText("当前文件: "+ fileName);
        bchanged = true;
        return true;
    }
    private void pageSet(){
        //打印设置
    }
    private void print(){
        //打印
    }
    private void fileExit(){
          int option = -1;
          Object options[] = {"Yes","No","Cancel"};
          if(bchanged) {//如果当前内容没有保存,提示是否保存
              option = JOptionPane.showOptionDialog(frame,"是否保存文件?","exit",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[0]);
              }
          switch(option) {
              case JOptionPane.YES_OPTION:
                if(fileName != null)  fileSave();
                else fileSaveTo();
                System.exit(0);
              case JOptionPane.CANCEL_OPTION:
                return;
              default:
                System.exit(0);
        }
    }
    private void dateTime(){
        Calendar today=new GregorianCalendar();
        int today_year=today.get(Calendar.YEAR);
        int today_month=today.get(Calendar.MONTH);
        int today_day=today.get(Calendar.DAY_OF_MONTH);
        textArea.insert(today_year+"-"+today_month+"-"+today_day,textArea.getCaretPosition());
    }
    //设置颜色
    private void setColor(){
        //弹出颜色色选择器对话框
        Color color=JColorChooser.showDialog(textArea, "选择颜色", Color.BLACK);
        textArea.setForeground(color);
    }
    private void fileCount(){
        JFrame fileCount = new JFrame("统计结果");
        JPanel panel = new JPanel();
        JLabel label1 = new JLabel();
        JLabel label2 = new JLabel();
        panel.setLayout(new GridLayout(2,1));
        panel.add(label1);
        panel.add(label2);
        fileCount.add(panel,BorderLayout.CENTER);
        fileCount.setSize(300,120);
        fileCount.setLocation(300,200);
        fileCount.setVisible(true);
        fileCount.setResizable(false);
        label1.setText("行数:"+textArea.getLineCount());//文本区中所包含的行数。
        label2.setText("字符数(含空格):"+textArea.getText().length());
    }
    private void fileFind(){
        JFrame find = new JFrame("查找");
        JLabel label = new JLabel("请输入查找的字符串");
        final JTextField text = new JTextField(10);
        JButton button = new JButton("查找");
        find.setLayout(new FlowLayout());
        find.add(label);
        find.add(text);
        find.add(button);
        find.setSize(300,90);
        find.setLocation(300,200);
        find.setVisible(true);
        find.setResizable(false);//不可改变大小
        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String src=text.getText();
                String desc=textArea.getText();
                if(desc.indexOf(src)==-1){
                    JFrame result = new JFrame("查找失败");
                    JLabel label= new JLabel("未找到查询结果");
                    result.add(label);
                    result.setSize(300,60);
                    result.setLocation(300,120);
                    result.setVisible(true);
                    result.setResizable(false);
                    //JOptionPane.showConfirmDialog(null, "NOT FOUNT!!");
                }else{
                    int start = desc.indexOf(src,mark);
                    mark = start +1;
                    if(mark!=0){
                      textArea.setSelectionStart(start);
                      textArea.setSelectionEnd(start+src.length());
                       }
                }
            }
        }
        );
    }
    private void fileReplace(){
        JFrame replace = new JFrame("替换");
        JLabel label1 = new JLabel("查   找:");
        JLabel label2 = new JLabel("替换为:");
        final JTextField text1 = new JTextField(10);
        final JTextField text2 = new JTextField(10);
        JButton button1 = new JButton("替换/替换下一个");
        JButton button2 = new JButton("全部替换");
        JPanel p1 = new JPanel();
        JPanel p2 = new JPanel();
        JPanel p3 = new JPanel();
        p1.add(label1);
        p1.add(text1);
        p2.add(label2);
        p2.add(text2);
        p3.add(button1);
        p3.add(button2);
        replace.setLayout(new GridLayout(3,1));
        replace.add(p1);
        replace.add(p2);
        replace.add(p3);
        replace.setSize(300,120);
        replace.setLocation(300,200);
        replace.setVisible(true);
        replace.setResizable(false);
        button1.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String find = text1.getText();
                String replace = text2.getText();
                String desc = textArea.getText();
                if(desc.indexOf(find)==-1){
                    JFrame result = new JFrame("查找失败");
                    JLabel label= new JLabel("未找到查询结果");
                    result.add(label);
                    result.setSize(300,60);
                    result.setLocation(300,120);
                    result.setVisible(true);
                    result.setResizable(false);
                }else{//javax.swing.text.JTextComponent
                    textArea.select(desc.indexOf(find), desc.indexOf(find)+find.length());
                    textArea.replaceSelection(replace);
                }
            }
        }
        );
        button2.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String find = text1.getText();
                String replace = text2.getText();
                String desc = textArea.getText();
                if(desc.indexOf(find)==-1){
                        JFrame result = new JFrame("查找失败");
                        JLabel label= new JLabel("未找到查询结果");
                        result.add(label);
                        result.setSize(300,60);
                        result.setLocation(300,120);
                        result.setVisible(true);
                        result.setResizable(false);
                    }else{
                        textArea.setText(textArea.getText().replaceAll(find,replace));
                    }
            }
        }
        );
    }
   
    private void about(){
        JFrame about = new JFrame("关于");
        JLabel label1 = new JLabel("版本:1.0");
        JLabel label2 = new JLabel("作者:zichen");
        JLabel label3 = new JLabel("web:bbs.korui.com");
        GridBagLayout layout = new GridBagLayout();
        about.setLayout(layout);
        GridBagConstraints n1 = new GridBagConstraints();
        n1.gridx = 0;
        n1.gridy = 0;
        n1.gridwidth = 10;
        n1.gridheight= 10;
        n1.anchor =        GridBagConstraints.WEST;
        GridBagConstraints n2 = new GridBagConstraints();
        n2.gridx = 0;
        n2.gridy = 10;
        n2.gridwidth = 10;
        n2.gridheight= 10;
        n2.anchor =        GridBagConstraints.WEST;
        GridBagConstraints n3 = new GridBagConstraints();
        n3.gridx = 0;
        n3.gridy = 20;
        n3.gridwidth = 10;
        n3.gridheight= 10;
        n3.anchor =        GridBagConstraints.WEST;
        layout.setConstraints(label1,n1);
        layout.setConstraints(label2,n2);
        layout.setConstraints(label3,n3);
        about.add(label1);
        about.add(label2);
        about.add(label3);
        about.setSize(300,200);
        about.setLocation(300,200);
        about.setVisible(true);
        about.setResizable(false);
    }
    public void showMe(){
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setSize(d.width,d.height);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
   
    public static void main(String[] args) {
        new NotePad().showMe();
    }
}

class refreshTime extends Thread{
    JLabel statBar4;
    public refreshTime(JLabel statBar){
        this.statBar4=statBar;
    }
    public void run(){
        while(true){
            GregorianCalendar time=new GregorianCalendar();
            statBar4.setText("当前时间:"+time.get(GregorianCalendar.HOUR_OF_DAY)+":"
                      +time.get(GregorianCalendar.MINUTE)+":"
                      +time.get(GregorianCalendar.SECOND));
             try {
                 Thread.sleep(1000);
     } catch (InterruptedException e) {e.printStackTrace();}
        }
    }
}

class Camera
{  
    private String fileName; //文件的前缀
    private String imageFormat; //图像文件的格式
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    public Camera(String s,String format) {
      fileName = s;
      imageFormat=format;
        }
    public void snapShot() {
      try {
        BufferedImage screenshot = (new Robot()).createScreenCapture(new
                Rectangle(0, 0, (int) d.getWidth(), (int) d.getHeight()));
        String name=fileName+"."+imageFormat;//根据文件前缀变量和文件格式变量,自动生成文件名 
        File f = new File(name);
        ImageIO.write(screenshot, imageFormat, f);//将screenshot对象写入图像文件 
      }catch (Exception ex) {System.out.println(ex);}
            }
}

class font{
    private JTextArea textArea;
    private JButton ok,cancel;
    private JComboBox fontName,fontSize,fontStyle;
    GraphicsEnvironment ge;//定义系统字体对象
    String[]    size = {"8","10","12","14","16","18","20","22","24","26","28","32","36","48","72","96"};
    String[]    style= {"PLAIN","BOLD","ITALIC"};
    JFrame jf = new JFrame("字体设置");
    public font(JTextArea textArea){
        this.textArea=textArea;
        JLabel label1=new JLabel("    字体                                         ");
        JLabel label2=new JLabel(" 字号        ");
        JLabel label3=new JLabel(" 样式        ");
        ge = GraphicsEnvironment.getLocalGraphicsEnvironment();//获取系统字体
        String[] fontname = ge.getAvailableFontFamilyNames();
        fontName = new JComboBox(fontname);
        fontSize = new JComboBox(size);
        fontStyle = new JComboBox(style);
        ok = new JButton("确定");
        cancel = new JButton("取消");
        jf.setLayout(new BorderLayout());
        JPanel p1 = new JPanel();
        JPanel p2 = new JPanel();
        JPanel p3 = new JPanel();
        p1.add(label1);
        p1.add(label2);
        p1.add(label3);
        p2.add(fontName);
        p2.add(fontSize);
        p2.add(fontStyle);
        p3.add(ok);
        p3.add(cancel);
        jf.add(p1,BorderLayout.NORTH);
        jf.add(p2,BorderLayout.CENTER);
        jf.add(p3,BorderLayout.SOUTH);
        jf.setSize(360,200);
        jf.setLocation(300,200);
        jf.setVisible(true);
        jf.setResizable(false);
        addEventHandler();
    }
    private void addEventHandler(){
        ok.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                String n1 = (String)fontName.getSelectedItem();
                int  n2 = fontStyle.getSelectedIndex();
                String n3 = (String)fontSize.getSelectedItem();
                textArea.setFont(new Font(n1,n2,Integer.parseInt(n3)));
            }
        });
        cancel.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                jf.setVisible(false);//
            }
        }       
        );
    }
}