记事本

package Src;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.*;

@SuppressWarnings({ "serial", "unused" })
public class MyNotepad extends JFrame implements ActionListener{

 JTextArea text = new JTextArea();              //字段摘要 
 JMenuBar menubar = new JMenuBar();
 JMenu files = new JMenu("文件");
 JMenu edit = new JMenu("编辑");
 JMenu formats = new JMenu("格式");
 JMenu view = new JMenu("查看");
 JMenu helps = new JMenu("帮助");
 JMenuItem newFile = new JMenuItem("新建");
 JMenuItem open = new JMenuItem("打开");
 JMenuItem save = new JMenuItem("保存");
 JMenuItem saveAs = new JMenuItem("另存为");
 JMenuItem exit = new JMenuItem("退出");
 JMenuItem cut = new JMenuItem("剪切");
 JMenuItem copy = new JMenuItem("复制");
 JMenuItem paste = new JMenuItem("粘贴");
 JMenuItem delete = new JMenuItem("删除");
 JMenuItem find = new JMenuItem("查找");
 JMenuItem findNext = new JMenuItem("查找下一个");
 JMenuItem replace = new JMenuItem("替换");
 JMenuItem selectAll = new JMenuItem("全选");
 JMenuItem timeDate = new JMenuItem("时间/日期");
 JCheckBoxMenuItem lineWrap = new JCheckBoxMenuItem("自动换行");
 JMenuItem fonts = new JMenuItem("字体");
 JCheckBoxMenuItem state = new JCheckBoxMenuItem("状态栏");
 JMenuItem about = new JMenuItem("关于记事本");
 String name="新建记事本";                 // 保存标题名
 String openedPath = null;                 // 系统保存的打开路径
 boolean isChangered = false;                //是否被改动过,true表示改过,false表示未改动过
 boolean isOpened = false;                 //表示打开的text,false表示新建的text
 String findStr = null;                  // 保存要查找的字符串
 public MyNotepad(String name)
 {                       //构造函数
  super(name);   
  this.setSize(600, 500);
  this.setLocation(200,200);
  windowAdapter winAda = new windowAdapter();           //接收窗口事件的抽象适配器类
  this.addWindowListener(winAda);  

  menubar.add(files);                 //添加控键
  menubar.add(edit);
  menubar.add(formats);
  menubar.add(view);
  menubar.add(helps);
  files.add(newFile);
  files.add(open);
  files.add(save);
  files.add(saveAs);
  files.addSeparator();
  files.add(exit);

  edit.addSeparator();
  edit.add(cut);
  edit.add(copy);
  edit.add(paste);
  edit.add(delete);
  edit.addSeparator();
  edit.add(find);
  edit.add(findNext);
  edit.add(replace);
  edit.addSeparator();
  edit.add(selectAll);
  edit.add(timeDate);
  formats.add(lineWrap);
  formats.add(fonts);
  view.add(state);
  helps.add(about);
  this.setJMenuBar(menubar);
  this.add(new JScrollPane(text));
  DocumentListener docuLis = new documentListener();          //该接口接收文本文档的更改通知。
  text.getDocument().addDocumentListener(docuLis);
                       //增加监听
  newFile.addActionListener( this);
  open.addActionListener(this);
  save.addActionListener(this);
  saveAs.addActionListener(this);
  exit.addActionListener(this);

  cut.addActionListener(this);
  copy.addActionListener(this);
  paste.addActionListener(this);
  delete.addActionListener(this);
  find.addActionListener(this);
  findNext.addActionListener(this);
  replace.addActionListener(this);
  selectAll.addActionListener(this);
  timeDate.addActionListener(this);
  lineWrap.addActionListener(this);
  fonts.addActionListener(this);
  state.addActionListener(this);
  about.addActionListener(this);
  
  state.setEnabled(false);  
 }

 

/**
* 专门进行保存处理的函数,通过判断两个变量判断是:保存,另存为,不作任何操作
* @param isChangered text是否被改动过,true表示改过,false表示未改动过
* @param isOpened true表示打开的text,false表示新建的text
* @param openedPath 如果文档是打开的或已经保存,则有保存的路径,
*/
 void save(boolean isChangered, boolean isOpened)
 {
  String savePath = new String();
  if (isChangered && isOpened)
  {                      // 文件保存
   if (JOptionPane.showConfirmDialog(MyNotepad.this, "需要保存文件吗?","保存提示", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
   {                
    try {
      savePath = openedPath;
      FileOutputStream fos = new FileOutputStream(savePath);     //创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
      BufferedOutputStream bufferedOutput = new BufferedOutputStream(fos); //创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
      bufferedOutput.write(text.getText().getBytes());
      bufferedOutput.close();
      fos.close();
      this.isChangered = false;
      this.isOpened = true;
     } catch (Exception ex)
     {
      ex.printStackTrace();
     }  
   } 
 } else if (isChangered && !isOpened)
 {                       //文件另存为
  savePath = null;
  if (JOptionPane.showConfirmDialog(MyNotepad.this, "需要保存文件吗?","另存为提示", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
  {
   FileDialog saveFile = new FileDialog(MyNotepad.this,"保存文件...", FileDialog.SAVE);
   saveFile.setVisible(true);
   if (saveFile.getDirectory() != null&& saveFile.getFile() != null)
   {
    savePath = saveFile.getDirectory() + saveFile.getFile();
   }  
   if (savePath != null)
   {
   try {
     FileOutputStream fos = new FileOutputStream(savePath);
     BufferedOutputStream bufferedOutput = new BufferedOutputStream(fos);
     bufferedOutput.write(text.getText().getBytes());
     bufferedOutput.close();
     fos.close();
     openedPath = savePath;
     this.isChangered = false;
     this.isOpened = true;
    }
   catch (Exception ex){
         ex.printStackTrace();
        }
   }
  }
 }
 }
 
 class windowAdapter extends WindowAdapter             //windows监听类
 {
  public void windowClosing(WindowEvent e)
  {  
   save(isChangered,isOpened);
   System.exit(0);
  }  
 }
 
 class documentListener implements DocumentListener           //文档监听接口,判断文档是否被改过
 {
 public void changedUpdate(DocumentEvent e)
  {
   isChangered = true;
  }
 
 public void insertUpdate(DocumentEvent e)
  {
   isChangered = true;
  }
 
 public void removeUpdate(DocumentEvent e)
  {
   isChangered = true;
  }
 }
 
 public void actionPerformed( ActionEvent e)
 {  
  if (e.getSource() == newFile)              //新建文件
  {
   save(isChangered, isOpened);
   text.setText("");
   MyNotepad.this.setTitle(name);
   isOpened = false;
   isChangered = false;
   openedPath = null;  
  }  
  else if (e.getSource() == exit)              //退出
  {
   save(isChangered, isOpened);
   System.exit(0);
  }
  else if (e.getSource() == cut)               //剪切
   text.cut();
  else if (e.getSource() == copy)              //拷贝
   text.copy();
  else if (e.getSource() == paste)              //粘贴
   text.paste();
  else if (e.getSource() == selectAll)             //选择全部
   text.selectAll();
  else if(e.getSource()==fonts)              //调用字体
   new font(text);
  else if (e.getSource() == timeDate)
  {                      //在文件中输出当前时间
   Date nowTime = new Date();
   SimpleDateFormat times = new SimpleDateFormat("HH:mm yyyy-MM-dd");
   text.insert(times.format(nowTime), text.getCaretPosition());
  }
 
  else if (e.getSource() == lineWrap)             //自动换行设置
   text.setLineWrap(true);
 
  else if (e.getSource() == about)
  {                      //关于记事本
   String message = "欢迎使用Java记事本!/n版权所有:KingZ_71...联系QQ:476938977";
   JOptionPane.showMessageDialog(MyNotepad.this,message, "关于...",JOptionPane.PLAIN_MESSAGE);
  }
 
  else if (e.getSource() == open)              //打开文件
  {           
   save(isChangered, isOpened);
   FileDialog openFile = new FileDialog(MyNotepad.this, "打开文件...",FileDialog.LOAD);
   openFile.setVisible(true);
   String filePath = null;
   if(openFile.getDirectory()!=null && openFile.getFile()!=null)
   {
    filePath = openFile.getDirectory() + openFile.getFile();
   }
   if (filePath!=null)
   {
    try {                    //进行文件操作
      FileInputStream fileInput = new FileInputStream(new File(filePath));
      BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
      byte[] contents = new byte[bufferedInput.available()];
      bufferedInput.read(contents);
      text.setText(new String(contents));
      text.setSelectionStart(0);
      text.setSelectionEnd(0);
      //Notepad.this.setTitle(openFile.getFile());
      openedPath = filePath;
      bufferedInput.close();
      fileInput.close();
      isChangered = false;
      isOpened = true;
      MyNotepad.this.setTitle(openedPath+" "+name);
     }
    catch (FileNotFoundException e1)
    {
     e1.printStackTrace();
    }
    catch (IOException e2)
    {
     e2.printStackTrace();
    }
 
   }
 }
 
 else if (e.getSource() == save)
 {                        //保存
  if(text.getDocument().getLength()==0&&isOpened&&isChangered)  
   save(true, true);                  //执行保存
   else if(text.getDocument().getLength()==0&&!isOpened)  
    save(true, false);                     //执行另存为
     else
      save(isChangered, isOpened);
 }
 
 else if (e.getSource() == saveAs)
 {                        //另存为
  save(true, false);
 }
 else if(e.getSource() == delete) 
 {                        //删除
  int start;   
  int end;
  start = text.getSelectionStart();
  end = text.getSelectionEnd();
  text.replaceRange("", start, end);
 }
 
 else if (e.getSource() == find|| e.getSource() ==findNext)
 {                        //查找和查找下一个
  if(findStr==null || e.getSource()==find)
   {
   findStr = JOptionPane.showInputDialog(MyNotepad.this, "请输入要找的字符串!");
   if ((findStr!=null)&&!findStr.equals(""))
    {
     int position =text.getText().indexOf(findStr) ;
     if(position!=-1)
      {
       text.setSelectionStart(position);
       text.setSelectionEnd(position+findStr.length());
      }
  else JOptionPane.showMessageDialog(MyNotepad.this, "你需要查找的内容不存在!");
    } 
  else JOptionPane.showMessageDialog(MyNotepad.this, "必须输入待查找的字符串!");
   }
  else
  {
  if ((findStr!=null)&&!findStr.equals(""))
   {
    int position = text.getText().indexOf(findStr, text.getSelectionStart()+1) ;
    if(position!=-1)
    {
     text.setSelectionStart(position);
     text.setSelectionEnd(position+findStr.length());
    }
  else JOptionPane.showMessageDialog(MyNotepad.this, "你需要查找的内容不存在!");
   }
  else JOptionPane.showMessageDialog(MyNotepad.this, "必须要输入字符串!");
  }
 }
 
 else if (e.getSource() == replace)
 {                        //替换
  String findStr = null;
  String replaceStr;
  String str;
  int position;
  findStr = JOptionPane.showInputDialog(MyNotepad.this, "请输入要替换的字符串!");
  if ((findStr!=null)&&!findStr.equals(""))
  {
   position = text.getText().indexOf(findStr);
   if (position != -1)
   {
    text.setSelectionStart(position);
    text.setSelectionEnd(position + findStr.length());
    replaceStr = JOptionPane.showInputDialog(MyNotepad.this,"请输入替换的字符串!");
    if(replaceStr!=null)
    {
     str = text.getText().replace(findStr, replaceStr);
     text.setText(str);
    }
   }
   else JOptionPane.showMessageDialog(MyNotepad.this, "没有你要替换的字符串");
  }
  else JOptionPane.showMessageDialog(MyNotepad.this, "没有你想替换的的字符!");
 }  
 }
 
 class font{                       //字体设置
     private JTextArea textArea;
     private JButton ok,cancel;
     private JComboBox fontName,fontSize,fontStyle;
     GraphicsEnvironment ge;                   //定义系统字体对象
     String[]    size = {"10","12","14","16","18","20","22","24","26","28","32","36","40","100"};
     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)));
                 jf.setVisible(false);
             }
         });
         cancel.addActionListener(new ActionListener()
         {
             public void actionPerformed(ActionEvent e)
             {
                 jf.setVisible(false);//
             }
         }       
         );
     } 
 } 
 
 
 public static void main(String[] args) {               // 程序入口
 try {
   UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName());      //指定外观
  }
 catch (Exception e)
  {  
   System.err.println(e);                  //错误输出流
  }
 MyNotepad notepad = new MyNotepad("记事本");
 notepad.setVisible(true);
 }
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值