[学习笔记]java SE 学习时候做的一个记事本实例(功能不全)自认为文件读和写还不错

本文介绍了一个使用Java Swing实现的简易记事本程序,具备基本的文件操作功能,如打开、保存、另存为等,并集成了简单的编辑功能。文章详细展示了如何通过图形界面进行文件读写操作。

package cn.java;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author MASA
 * @version 0.2
 * 这是第一个版本
 * 功能:显示最基本窗体
 * 小新功能,风格显示窗体
 */
public class JNotePad extends JFrame{
 
 //File菜单里图片
 private static ImageIcon iconOpen,iconSave,iconSaveAs,iconClose,iconPrint;
 //编辑菜单里图片
 private static ImageIcon iconCut,iconCopy,iconPaste;
 //简介
 private static ImageIcon iconAbout;
 
 
 private JMenuBar menuBar;
 //菜单
 private JMenu fileMenu,editMenu,aboutMenu;
 //文件菜单
 private JMenuItem menuOpen,menuSave,menuSaveAs,menuClose,menuPrint;
 //编辑菜单
 private JMenuItem menuCut,menuCopy,menuPaste;
 //about
 private JMenuItem menuAbout;
 
 /**
  *
  * @param 工具栏
  */
 private JToolBar toolBar;
 private JButton toolOpen,toolSave,toolPrint;
 
 private JTextArea textarea;
 private JLabel stateBar;
 private JPopupMenu popUpMenu;
 
 public JNotePad(String title){
  super(title);
  //initResource();
  setUpUIComponent();
  setUpEventListener();
 }
 /**
  * 现在这个类有几个方法
  * 第一考虑,资源加进来:图片
  */
 static{
 //private void initResource(){
  //加载图标资源
  //JNotePad.class.getResource();
  iconOpen  = new ImageIcon(JNotePad.class.getResource("images/open.gif"));
  iconCopy  = new ImageIcon(JNotePad.class.getResource("images/copy.gif"));
  iconCut  = new ImageIcon(JNotePad.class.getResource("images/cut.gif"));
  iconAbout  = new ImageIcon(JNotePad.class.getResource("images/logo.jpg"));
  iconPaste  = new ImageIcon(JNotePad.class.getResource("images/paste.gif"));
  iconPrint  = new ImageIcon(JNotePad.class.getResource("images/print.gif"));
  iconSave  = new ImageIcon(JNotePad.class.getResource("images/save.gif"));
  iconSaveAs  = new ImageIcon(JNotePad.class.getResource("images/saveas.gif"));
  iconClose  = new ImageIcon(JNotePad.class.getResource("images/close.gif"));
 }
 /**
  * 第二步:整个Component组件
  * 菜单,菜单项。。工具栏
  */
 private void setUpUIComponent(){
  this.setSize(640,480);
  this.setLocation(100,100);
  //菜单栏
  menuBar = new JMenuBar();
  this.setJMenuBar(menuBar);
  //菜单
  fileMenu = new JMenu("文件");
  editMenu = new JMenu("编辑");
  aboutMenu = new JMenu("About");
  
  menuBar.add(fileMenu);
  menuBar.add(editMenu);
  menuBar.add(aboutMenu);
  
  //文件菜单项
  menuOpen = new JMenuItem("打开",iconOpen);
  menuSave = new JMenuItem("保存",iconSave);
  menuSaveAs = new JMenuItem("另存为",iconSaveAs);
  menuClose = new JMenuItem("关闭",iconClose);
  menuPrint = new JMenuItem("打印",iconPrint);
  
  fileMenu.add(menuOpen);
  fileMenu.add(menuSave);
  fileMenu.add(menuSaveAs);
  fileMenu.add(menuClose);
  fileMenu.add(menuPrint);
  //编辑菜单项
  menuCut = new JMenuItem("剪切",iconCut);
  menuCopy = new JMenuItem("复制",iconCopy);
  menuPaste = new JMenuItem("粘贴",iconPaste);
  
  editMenu.add(menuCut);
  editMenu.add(menuCopy);
  editMenu.add(menuPaste);
  //About菜单项
  menuAbout = new JMenuItem("About",iconAbout);
  aboutMenu.add(menuAbout);
  
  //工具栏
  toolBar = new JToolBar();
  toolOpen = new JButton("打开",iconOpen);
  toolSave = new JButton("保存",iconSave);
  toolPrint = new JButton("打印",iconPrint);
  toolBar.add(toolOpen);
  toolBar.add(toolSave);
  toolBar.add(toolPrint);
  
  this.setLayout(new BorderLayout());
  this.add(toolBar,BorderLayout.NORTH);
  
  //编辑区
  textarea = new JTextArea();
  this.add(new JScrollPane(textarea),BorderLayout.CENTER);
  
  stateBar = new JLabel("未定义");
  this.add(stateBar,BorderLayout.SOUTH);
  
  //鼠标右击
  popUpMenu = editMenu.getPopupMenu();
 }
 /**
  * 第三步:处理监听操作
  */
 private void setUpEventListener(){
  this.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e){
    closeWindows();
   }});
  
  menuClose.addActionListener(new ActionListener(){

  
   public void actionPerformed(ActionEvent e) {
         closeWindows();
    
   }
   
  });
  menuOpen.addActionListener(new ActionListener(){

   public void actionPerformed(ActionEvent e) {
      Component parent=(Component) e.getSource();
    openFile(parent);
   }});
  toolOpen.addActionListener(new ActionListener(){

   public void actionPerformed(ActionEvent e) {
      Component parent=(Component) e.getSource();
    openFile(parent);
   }});
  menuOpen.addActionListener(new ActionListener(){

  
   public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    saveFile();
   }
   
  });
 
  toolSave.addActionListener(new ActionListener(){

  
   public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    saveFile();
   }
   
  });
 
  }
 
  
 /**
  * 关闭窗口的方法
  * */
 
 public void closeWindows()
 {
   int answer = JOptionPane.showConfirmDialog(null, "退出","询问",JOptionPane.YES_NO_OPTION);
   if(answer == JOptionPane.YES_OPTION ){
    System.exit(0);
   }else{
    setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
   }
  }
 
 /**
  * 打开文件的方法
  *
  * */
 public void  openFile(Component parent){
   JFileChooser chooser = new JFileChooser();
      FileNameExtensionFilter filter = new FileNameExtensionFilter(
          "*.txt", "txt");
     chooser.setFileFilter(filter);
      int returnVal = chooser.showOpenDialog(parent);
      if(returnVal == JFileChooser.APPROVE_OPTION) {
       BufferedReader in=null;
           String filePath=chooser.getSelectedFile().getPath();
           File openFileName=null;
           FileReader fr=null;
           try {
           openFileName=new File(filePath);
           
            int size=(int)openFileName.length();
            char[] fileSize=new char[size];
            int charsRead=0;
           fr= new FileReader(openFileName);
     in= new BufferedReader(fr);
        while(in.ready()){
         charsRead += in.read(fileSize, charsRead, size-charsRead);
         }
        textarea.setText(new String(fileSize,0,charsRead));
    } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }finally{
     try {
      if(in!=null){
       in.close();
      in=null;
      }
      if(fr!=null){
       fr.close();
          fr=null;
      }
      this.setTitle(filePath);
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }

      }
}
 public void saveFile(){
   JFileChooser saveF = new JFileChooser();
   NoteFilter noteF=new NoteFilter();
  
  saveF.setFileFilter(noteF);
  
   boolean panduan=true;
   do{
    int result=saveF.showSaveDialog(this);
   if(result==JFileChooser.APPROVE_OPTION ){
     String filePath=saveF.getSelectedFile().getPath();
    
   
     /**想办法实现文件类型处出现.txt;
      * */  filePath=filePath.trim();
      int len=filePath.indexOf('.');
    
      if(len==-1)
      filePath= filePath+".txt";
     File file=new File(filePath);
    if(file.exists()){
     String lineSeparator=System.getProperty("line.separator");
                  int resultShow=JOptionPane.showConfirmDialog(null,filePath+"已存在"+lineSeparator+"是否要替换它?", "另存为", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
      if( resultShow==JOptionPane.YES_OPTION){
       saveString(filePath);
       panduan=false;
      }else{
       continue;
      }
               
    }
    else{
      try {
      if(file.createNewFile()){
       saveString(filePath);
      }
      panduan=false;
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    
 }
   }while(panduan);
 }
 public void saveString (String filePath){
  
  
   BufferedWriter bw=null;
   FileWriter fw=null;
   try {
    fw=new FileWriter(filePath);
    bw=new BufferedWriter(fw);
    int fileSize=textarea.getText().length();
    char[] fileBuffer=new char[fileSize];
    textarea.getText().getChars(0, fileSize, fileBuffer, 0);
    bw.write(fileBuffer, 0, fileSize);
   
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   this.setTitle(filePath);
    try {
     if(bw!=null){
      
     bw.close();
     bw=null;
     }
     if(fw!=null){
      fw.close();
      fw=null;
     }
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    
   }

}

 
 
 
 class NoteFilter extends FileFilter{

  @Override
  public boolean accept(File f) {
   // TODO Auto-generated method stub
   
   return f.getName().endsWith(".txt");
  }

  @Override
  public String getDescription() {
   // TODO Auto-generated method stub
   return "文本文档(.txt)";
  } 
 }
 public static void main(String args[]){
  try{
   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  }catch(Exception e){
   JOptionPane.showMessageDialog(null, e.getMessage(),"Info.",JOptionPane.INFORMATION_MESSAGE);
  }
  new JNotePad("记事本").setVisible(true);
 }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值