java实现Windows记事本

Posted feiquan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java实现Windows记事本相关的知识,希望对你有一定的参考价值。

给大家分享下我之前的作品:

源文件下载:

  链接:https://pan.baidu.com/s/1N45VsS9aVgmvhvYjRLxBrA 
  提取码:b9fg 

 

源码:

  JF_Notpad.java实现主要面板,在二级菜单可以实现java模板建立,可以后期自己添加:

  

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;    //导入菜单
import javax.swing.filechooser.FileNameExtensionFilter;
import java.util.Date;    //获取系统的时间
import java.text.SimpleDateFormat;    //控制系统的时间格式

import java.awt.event.*;
import java.io.*;
import java.util.regex.*;

public class JF_Notpad extends JFrame implements ActionListener,WindowListener{
    //menuBar
    private    JMenuBar mb;
    private JMenu file,edit,format,view,help;
    
    //menuToolBar
    private JToolBar tool;
    private    static int BUTTONWIDTH,BUTTONHEIGHT;
    private JButton create,unfold,copy,cut,paste,pasteShortcut,delete;
    
    
    //File
    //JMenu下还可以有二级菜单
    private JMenu newNot;
    //JMenuItem不可以有其他菜单
    private JMenuItem notpad,model,open,save,saveAs,pageSet,print,exit;
    
    //Edit
    private JMenuItem undoE,cutE,copyE,pasteE,deleteE,findE,findNextE,replaceE,goToE,selectAllE,timeDateE;
    
    //Format
    private JMenuItem     wordWrap,font;
    
    //View
    private JMenuItem     statusBar;
    
    //Help
    private JMenuItem     viewHelp,about;
    
    //leftSpace
    private JPanel leftSpace;
    
    //TextArea
    private JTextArea content;
    private JScrollPane scroll;
    
    //openUrl,saveUrl
    private static String openUrl="E:/notpad.txt";    //保存之前打开文件的路径
    private static String saveUrl="E:/notpad.txt";    //保存之前保存文件的路径
    private boolean saved=false;    //判断文件是否保存过
    
    //contentFont 字体
    private Font contentFont;
    
    
    //是否在打开保存面板后,还应该打开选择文件面板
    private boolean openFileBool=false;
    
    public static void main(String[] args) {
        JF_Notpad not=new JF_Notpad();
    }
    
    public static JButton changeIconSize(JButton button,String url,int width,int height,String tip){
        button.setBounds(0,0,width,height);
        ImageIcon buttonImg=new ImageIcon(url);
        //改变图片的大小
        Image temp=buttonImg.getImage().getScaledInstance(button.getWidth(), button.getHeight(), buttonImg.getImage().SCALE_DEFAULT);
        button=new JButton(new ImageIcon(temp));
        button.setToolTipText(tip);    //提示
        
        return button;
    }
    
    public static Image changeImageSize(String url,int width,int height){
        ImageIcon Img=new ImageIcon(url);
        //改变图片的大小
        Image temp=Img.getImage().getScaledInstance(width, height, Img.getImage().SCALE_DEFAULT);
        
        return temp;
    }
    
    JF_Notpad(){
        //menubar
        mb=new JMenuBar();
        file=new JMenu("File(F)");
        file.setMnemonic(\'F\');
        edit=new JMenu("Edit(E)");
        edit.setMnemonic(\'E\');
        format=new JMenu("Format(O)");
        format.setMnemonic(\'O\');
        view =new JMenu("View(V)");
        view.setMnemonic(\'V\');
        help=new JMenu("Help(H)");
        help.setMnemonic(\'H\');
        
        //menuToolBar
        tool=new JToolBar();
        BUTTONWIDTH=22;
        BUTTONHEIGHT=22;
        
        create=new JButton();
        create=JF_Notpad.changeIconSize(create, "img/notpad/news.png", BUTTONWIDTH, BUTTONWIDTH, "New");
        unfold=new JButton();
        unfold=JF_Notpad.changeIconSize(unfold, "img/notpad/open.png", BUTTONWIDTH, BUTTONWIDTH, "Open");
        copy=new JButton();
        copy=JF_Notpad.changeIconSize(copy, "img/notpad/copy.png", BUTTONWIDTH, BUTTONWIDTH, "Copy");
        cut=new JButton();
        cut=JF_Notpad.changeIconSize(cut, "img/notpad/cut.png", BUTTONWIDTH, BUTTONWIDTH, "Cut");
        paste=new JButton();
        paste=JF_Notpad.changeIconSize(unfold, "img/notpad/paste.png", BUTTONWIDTH, BUTTONWIDTH, "Paste");
        pasteShortcut=new JButton();
        pasteShortcut=JF_Notpad.changeIconSize(pasteShortcut, "img/notpad/pasteShortcut.png", BUTTONWIDTH, BUTTONWIDTH, "PasteShortcut");
        delete=new JButton();
        delete=JF_Notpad.changeIconSize(delete, "img/notpad/delete.png", BUTTONWIDTH, BUTTONWIDTH, "Delete");
        
        //menuToolBarListener
        create.setActionCommand("notpad");
        create.addActionListener(this);
        unfold.setActionCommand("open");
        unfold.addActionListener(this);
        copy.setActionCommand("copyE");
        copy.addActionListener(this);
        cut.setActionCommand("cutE");
        cut.addActionListener(this);
        paste.setActionCommand("pasteE");
        paste.addActionListener(this);
        pasteShortcut.setActionCommand("pasteShortcut");
        pasteShortcut.addActionListener(this);
        delete.setActionCommand("deleteE");
        delete.addActionListener(this);
        
        //file
        newNot=new JMenu("New(N)");
        newNot.setMnemonic(\'N\');
        ImageIcon icon=new ImageIcon(this.changeImageSize("img/notpad/logo.png", BUTTONWIDTH-5,BUTTONHEIGHT-5 ));
        notpad=new JMenuItem("Notpad",icon);
        model=new JMenuItem("Model");
        icon=new ImageIcon(this.changeImageSize("img/notpad/open.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        open=new JMenuItem("Open",icon);
        icon=new ImageIcon(this.changeImageSize("img/notpad/save.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        save=new JMenuItem("Save",icon);
        icon=new ImageIcon(this.changeImageSize("img/notpad/saveAs.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        saveAs=new JMenuItem("Save As...",icon);
        pageSet=new JMenuItem("PageSet");
        print=new JMenuItem("Print");
        icon=new ImageIcon(this.changeImageSize("img/notpad/exit.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        exit=new JMenuItem("Exit",icon);
        
        //FileListener
        notpad.setActionCommand("notpad");
        notpad.addActionListener(this);
        model.setActionCommand("model");
        model.addActionListener(this);
        open.setActionCommand("open");
        open.addActionListener(this);
        save.setActionCommand("save");
        save.addActionListener(this);
        saveAs.setActionCommand("saveAs");
        saveAs.addActionListener(this);
        pageSet.setActionCommand("pageSet");
        pageSet.addActionListener(this);
        print.setActionCommand("print");
        print.addActionListener(this);
        exit.setActionCommand("exit");
        exit.addActionListener(this);
        
        //Edit    
        undoE=new JMenuItem("Undo");
        icon=new ImageIcon(this.changeImageSize("img/notpad/cut.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        cutE=new JMenuItem("Cut",icon);
        icon=new ImageIcon(this.changeImageSize("img/notpad/copy.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        copyE=new JMenuItem("Copy",icon);
        icon=new ImageIcon(this.changeImageSize("img/notpad/paste.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        pasteE=new JMenuItem("Paste",icon);
        icon=new ImageIcon(this.changeImageSize("img/notpad/delete.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        deleteE=new JMenuItem("Delete",icon);
        findE=new JMenuItem("Find...");
        findNextE=new JMenuItem("Find Next");
        replaceE=new JMenuItem("Replace...");
        goToE=new JMenuItem("Go To..");
        selectAllE=new JMenuItem("Select All");
        timeDateE=new JMenuItem("Time/Data");
        
        //EditListener
        undoE.setActionCommand("undoE");
        undoE.addActionListener(this);
        cutE.setActionCommand("cutE");
        cutE.addActionListener(this);
        copyE.setActionCommand("copyE");
        copyE.addActionListener(this);
        pasteE.setActionCommand("pasteE");
        pasteE.addActionListener(this);
        deleteE.setActionCommand("deleteE");
        deleteE.addActionListener(this);
        findE.setActionCommand("findE");
        findE.addActionListener(this);
        findNextE.setActionCommand("findNextE");
        findNextE.addActionListener(this);
        replaceE.setActionCommand("replaceE");
        replaceE.addActionListener(this);
        goToE.setActionCommand("goToE");
        goToE.addActionListener(this);
        selectAllE.setActionCommand("selectAllE");
        selectAllE.addActionListener(this);
        timeDateE.setActionCommand("timeDateE");
        timeDateE.addActionListener(this);
        
        //Format
        icon=new ImageIcon(this.changeImageSize("img/notpad/wordWrap.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        wordWrap=new JMenuItem("Word Wrap",icon);
        icon=new ImageIcon(this.changeImageSize("img/notpad/font.png", BUTTONWIDTH-8, BUTTONHEIGHT-8));
        font=new JMenuItem("Font...",icon);
        
        //FormatListener
        wordWrap.setActionCommand("wordWrap");
        wordWrap.addActionListener(this);
        font.setActionCommand("font");
        font.addActionListener(this);
        
        //View
        statusBar=new JMenuItem("Status Bar");
        
        //ViewListener
        statusBar.setActionCommand("statusBar");
        statusBar.addActionListener(this);
        
        //Help
        viewHelp=new JMenuItem("View Help");
        icon=new ImageIcon(this.changeImageSize("img/notpad/about.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
        about=new JMenuItem("About NotePad",icon);
        
        //HelpListener
        viewHelp.setActionCommand("viewHelp");
        viewHelp.addActionListener(this);
        about.setActionCommand("about");
        about.addActionListener(this);
        
        //leftSpace
        leftSpace=new JPanel();
        
        //contentFont 
        contentFont=new Font("KaiTi",Font.PLAIN,20);
        
        //textArea
        content=new JTextArea();
        content.setFont(contentFont);
        scroll=new JScrollPane(content);
        //scroll.setHorizontalScrollBar(content);
        
        //openUrl,saveUrl
//        openUrl="E:/notpad.txt";
//        saveUrl="E:/notpad.txt";
//        saved=false;
        
        //saveFilePanel
//        Save saveF=new Save("Save",this);
        
        //添加组件,从下一级开始装
        newNot.add(notpad);    newNot.add(model);
        file.add(newNot);    file.add(open);    file.add(save);    file.add(saveAs);    file.addSeparator();    file.add(pageSet);    file.add(print);    file.addSeparator();    file.add(exit);
        
        edit.add(undoE);
        edit.addSeparator();
        edit.add(cutE);
        edit.add(copyE);
        edit.add(pasteE);
        edit.add(deleteE);
        edit.addSeparator();
        edit.add(findE);
        edit.add(findNextE);
        edit.add(replaceE);
        edit.add(goToE);
        edit.addSeparator();
        edit.add(selectAllE);
        edit.add(timeDateE);
        
        format.add(wordWrap);
        format.add(font);
        
        view.add(statusBar);
        
        help.add(viewHelp);
        help.addSeparator();
        help.add(about);
        

        mb.add(file);    mb.add(edit); mb.add(format);    mb.add(view);    mb.add(help);
        
        tool.add(create);    
        tool.add(unfold); 
        tool.add(copy);
        tool.add(cut);
        tool.add(paste);
        tool.add(pasteShortcut);
        tool.add(delete);
        
        this.setJMenuBar(mb);
        this.add(tool,BorderLayout.NORTH);
        this.add(leftSpace,BorderLayout.WEST);
        this.add(scroll);
        
        
        this.setTitle("Notpad");
        this.setIconImage(new ImageIcon("img/notpad/logo.png").getImage());
        this.setLocation(300,300);
        this.setSize(400,400);
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
        this.setVisible(true);
        
    }
    
    private String origContent=null;    //保存一开始的文件或者保存过的文件
    private String copyContent=null;
    @Override
    public void actionPerformed(ActionEvent e) {
        switch(e.getActionCommand()){
        case "notpad":{
            System.out.println("notpad");
            
            this.isChangeFile("txt");
            
        }break;

        case "model":{
            System.out.println("model");
            
            this.isChangeFile("java");
        }break;

        case "open":{
            System.out.println("open");
            //防止第一次打开空文件时,还没保存
            if(this.origContent==null){
                this.saved=true;
            }
            
            if(saved){
                this.openFilePanel();
            }else{
                Save saveF=new Save("Save",this);
                this.openFilePanel();
            }
            
            
            
        }break;

        case "save":{
            System.out.println("save");
            this.saveFile();
            //this.setSaved(true);
            
        }break;

        case "saveAs":{
            System.out.println("saveAs");
            
            String str=content.getText();
            //选择保存文件的路径
            JFileChooser fileChoose=null;
            if(saveUrl==null){
                fileChoose=new JFileChooser();
            }else{
                fileChoose=new JFileChooser(saveUrl);
            }
            FileNameExtensionFilter filter=new FileNameExtensionFilter("txt & java","java","txt");    //设置可以识别的文件
            fileChoose.setFileFilter(filter);
            fileChoose.setDialogTitle("Save File");
            fileChoose.showSaveDialog(save);
            fileChoose.setVisible(true);
            
            File outFile =fileChoose.getSelectedFile();
            saveUrl=fileChoose.getSelectedFile().getPath();
            PrintStream p=null;
            try{
                p=new PrintStream(outFile);
                System.setOut(p);
                System.out.print(str);
            }catch(Exception a){
                System.out.println("SaveAS File Error!!");
            }finally{
                p.close();
            }    
        }break;

        case "pageSet":{
            System.out.println("pageSet");
            
        }break;

        case "print":{
            System.out.println("print");
            
        }break;

        case "exit":{
            System.out.println("exit");
            
            System.exit(-1);
        }break;

        case "undoE":{
            System.out.println("undoE");
            
        }break;

        case "cutE":{
            System.out.println("cutE");
            if(this.content.getSelectedText()!=null){
                this.copyContent=this.content.getSelectedText();
            }
            this.content.replaceSelection("");
        }break;

        case "copyE":{
            System.out.println("copyE");
            if(this.content.getSelectedText()!=null){
                this.copyContent=this.content.getSelectedText();
            }
            
        }break;

        case "pasteE":{
            System.out.println("pasteE");
            if(copyContent!=null){
                this.content.replaceRange("", content.getSelectionStart(), content.getSelectionEnd());
            }
            this.content.insert(copyContent, this.content.getSelectionStart());
        }break;

        case "deleteE":{
            System.out.println("deleteE");
            
            this.content.replaceSelection("");
        }break;

        case "findE":{
            System.out.println("findE");
            
            
        }break;

        case "findNextE":{
            System.out.println("findNextE");
            
        }break;

        case "replaceE":{
            System.out.println("replaceE");
            
        }break;

        case "goToE":{
            System.out.println("goToE");
            
        }break;

        case "selectAllE":{
            System.out.println("selectAllE");
            
            this.content.selectAll();
        }break;

        case "timeDateE":{
            System.out.println("timeDateE");
            
            SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //System.out.println(df.format(new Date()));
            this.content.insert(df.format(new Date()), content.getSelectionStart());
        }break;

        case "wordWrap":{
            System.out.println("wordWrap");
            
            ImageIcon icon;
            if(this.content.getLineWrap()){
                this.content.setLineWrap(false);
                icon=new ImageIcon(this.changeImageSize("img/notpad/wordWrap.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
                this.wordWrap.setIcon(icon);
            }else{
                this.content.setLineWrap(true);
                icon=new ImageIcon(this.changeImageSize("img/notpad/wordWrapNo.png", BUTTONWIDTH-5, BUTTONHEIGHT-5));
                this.wordWrap.setIcon(icon);
            }
            
        }break;

        case "font":{
            System.out.println("font");
            
            FontPanel f=new FontPanel("Font",this);
            
//            this.content.setFont(new Font(f.getFontN(),f.getFontSytleN(),f.getSizeN()));
            
        }break;

        case "statusBar":{
            System.out.println("statusBar");
            
        }break;

        case "viewHelp":{
            System.out.println("viewHelp");
            
        }break;

        case "about":{
            System.out.println("about");
            
            About a=new About("About","1.0","feiquan","228332xxxxx@qq.com","xxx-xxxx-xxxx","https://www.baidu.com");
        }break;
        
        case "pasteShortcut":{
            System.out.println("pasteShortcut");
            
        }break;
        
        }
        
    }

    @Override
    public void windowOpened(WindowEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void windowClosing(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out .println("弹出是否选择保存的对话框");
        if(saved){
            Save saveF=new Save("Save",this);
        }
    }

    @Override
    public void windowClosed(WindowEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void windowIconified(WindowEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void windowActivated(WindowEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
        // TODO Auto-generated method stub
        
    }

    public static String getOpenUrl() {
        return openUrl;
    }

    public static void setOpenUrl(String openUrl) {
        JF_Notpad.openUrl = openUrl;
    }

    public static String getSaveUrl() {
        return saveUrl;
    }

    public static void setSaveUrl(String saveUrl) {
        JF_Notpad.saveUrl = saveUrl;
    }
    
    //保存文件其中包含了,判断文件是否存在
    public void saveFile(){
        String str=this.content.getText();
        System.out.println("正在保存:\\n"+str);
        
        //判断文件是否存在,不存在则创建文件
        File file=new File(openUrl);
        if(!file.exists()){
            try{
                file.createNewFile();
            }catch(Exception a){
                System.out.println("创建文件 "+file.getAbsolutePath()+" 失败!!");
            }
        }
        
        PrintStream p=null;
        try{
            p=new PrintStream(new File(openUrl));
            System.setOut(p);
            System.out.print(str);
            saved=true;
        }catch(Exception a){
            System.out.println("Save File Error!!");
            saved=false;
        }finally{
            p.close();
        }
        
    }
    
    //判断文件是否修改过,并根据传入的属性判断新建那个文件
    public void isChangeFile(String properties){
        System.out.println("是否保存文件:"+saved);
        //判断文件是否修改过
        if(!(this.content.getText().equals(origContent))){
            saved=false;
        }
        
        //如果内容为空,也视为已经保存
        if(this.content.getText()==null||this.content.getText().equals(""))saved=true;
        
        System.out.println("判断后是否保存文件:"+saved);
        if(saved){
            switch(properties){
            case "txt":{
                this.content.setText("");
                this.setTitle("notpad");
                origContent="";
            }break;
            case "java":{
                this.setTitle("notpad");
                String str="public class Notpad {\\n\\tpublic static void main (String[] ages) {\\n\\t\\t\\n\\t}\\n}";
                this.content.setText(str);
                
                origContent=str;
            }break; 
            }
            
        }else{
            System.out .println("弹出是否选择保存的对话框");
            Save saveF=new Save("Save",this);
            
        }
        System.out.println("经过保存面板后是否保存文件:"+saved);
    }
    
    //打开选择打开文件面板,并选择文件
    public void openFilePanel(){
        origContent=this.content.getText();
        //显示选择文件面板
        JFileChooser fileChoose=null;
        if(openUrl==null){
            fileChoose=new JFileChooser();
        }else{
            fileChoose=new JFileChooser(openUrl);
        }
        FileNameExtensionFilter filter=new FileNameExtensionFilter("txt & java","java","txt");
        fileChoose.setFileFilter(filter);
        fileChoose.setDialogTitle("Open File");
        fileChoose.showOpenDialog(null);
        fileChoose.setVisible(true);
        
        //得到文件
        String url=fileChoose.getSelectedFile().getAbsolutePath();    //得到选择文件的路径
        
        
        //设置保存面板显示的路径
        JF_Notpad.setOpenUrl(url);
        Save saveF=new Save("Save",this);
        saveF.setVisible(false);
        saveF.setUrl(url);
        JLabel temp=saveF.getUrlL();
        temp.setText(url+" ?");
        saveF.setUrlL(temp);
        
        String name=fileChoose.getSelectedFile().getName();
        this.setTitle(name+" - Notpad");    //设置主窗口标题
        
        //文件

以上是关于java实现Windows记事本的主要内容,如果未能解决你的问题,请参考以下文章

用java在记事本写东西怎么实现换行

JAVA的弹窗怎么做?

Java实现简单记事本

简单的记事本功能实现代码--(流读取器)

如何在java中打开记事本文件?

上机题目(初级)- 用数组实现记事本+光标和删除(Java)