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

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);
 }

}
 

import java.awt.BorderLayout; import java.awt.Container; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; 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.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.BorderFactory; 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.KeyStroke; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; public class JNotePadUI extends JFrame { private JMenuItem menuOpen; private JMenuItem menuSave; private JMenuItem menuSaveAs; private JMenuItem menuClose; private JMenu editMenu; private JMenuItem menuCut; private JMenuItem menuCopy; private JMenuItem menuPaste; private JMenuItem menuAbout; private JTextArea textArea; private JLabel stateBar; private JFileChooser fileChooser; private JPopupMenu popUpMenu; public JNotePadUI() { super("新建文本文件"); setUpUIComponent(); setUpEventListener(); setVisible(true); } private void setUpUIComponent() { setSize(640, 480); // 菜单栏 JMenuBar menuBar = new JMenuBar(); // 设置「文件」菜单 JMenu fileMenu = new JMenu("文件"); menuOpen = new JMenuItem("打开"); // 快捷键设置 menuOpen.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_O, InputEvent.CTRL_MASK)); menuSave = new JMenuItem("保存"); menuSave.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_S, InputEvent.CTRL_MASK)); menuSaveAs = new JMenuItem("另存为"); menuClose = new JMenuItem("关闭"); menuClose.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, InputEvent.CTRL_MASK)); fileMenu.add(menuOpen); fileMenu.addSeparator(); // 分隔线 fileMenu.add(menuSave); fileMenu.add(menuSaveAs); fileMenu.addSeparator(); // 分隔线 fileMenu.add(menuClose); // 设置「编辑」菜单 JMenu editMenu = new JMenu("编辑"); menuCut = new JMenuItem("剪切"); menuCut.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK)); menuCopy = new JMenuItem("复制"); menuCopy.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK)); menuPaste = new JMenuItem("粘贴"); menuPaste.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK)); editMenu.add(menuCut); editMenu.add(menuCopy); editMenu.add(menuPaste); // 设置「关于」菜单 JMenu aboutMenu = new JMenu("关于"); menuAbout = new JMenuItem("关于JNotePad"); aboutMenu.add(menuAbout); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(aboutMenu); setJMenuBar(menuBar); // 文字编辑区域 textArea = new JTextArea(); textArea.setFont(new Font("宋体", Font.PLAIN, 16)); textArea.setLineWrap(true); JScrollPane panel = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); Container contentPane = getContentPane(); contentPane.add(panel, BorderLayout.CENTER); // 状态栏 stateBar = new JLabel("未修改"); stateBar.setHorizontalAlignment(SwingConstants.LEFT); stateBar.setBorder( BorderFactory.createEtchedBorder()); contentPane.add(stateBar, BorderLayout.SOUTH); popUpMenu = editMenu.getPopupMenu(); fileChooser = new JFileChooser(); } private void setUpEventListener() { // 按下窗口关闭钮事件处理 addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { closeFile(); } } ); // 菜单 - 打开 menuOpen.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } } ); // 菜单 - 保存 menuSave.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { saveFile(); } } ); // 菜单 - 另存为 menuSaveAs.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { saveFileAs(); } } ); // 菜单 - 关闭文件 menuClose.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { closeFile(); } } ); // 菜单 - 剪切 menuCut.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cut(); } } ); // 菜单 - 复制 menuCopy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { copy(); } } ); // 菜单 - 粘贴 menuPaste.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { paste(); } } ); // 菜单 - 关于 menuAbout.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // 显示对话框 JOptionPane.showOptionDialog(null, "程序名称:\n JNotePad \n" + "程序设计:\n \n" + "简介:\n 一个简单的文字编辑器\n" + " 可作为验收Java的实现对象\n" + " 欢迎网友下载研究交流\n\n" + " /", "关于JNotePad", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); } } ); // 编辑区键盘事件 textArea.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { processTextArea(); } } ); // 编辑区鼠标事件 textArea.addMouseListener( new MouseAdapter() { public void mouseReleased(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON3) popUpMenu.show(editMenu, e.getX(), e.getY()); } public void mouseClicked(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) popUpMenu.setVisible(false); } } ); } private void openFile() { if(isCurrentFileSaved()) { // 文件是否为保存状态 open(); // 打开 } else { // 显示对话框 int option = JOptionPane.showConfirmDialog( null, "文件已修改,是否保存?", "保存文件?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); switch(option) { // 确认文件保存 case JOptionPane.YES_OPTION: saveFile(); // 保存文件 break; // 放弃文件保存 case JOptionPane.NO_OPTION: open(); break; } } } private boolean isCurrentFileSaved() { if(stateBar.getText().equals("未修改")) { return false; } else { return true; } } private void open() { // fileChooser 是 JFileChooser 的实例 // 显示文件选取的对话框 int option = fileChooser.showDialog(null, null); // 使用者按下确认键 if(option == JFileChooser.APPROVE_OPTION) { try { // 开启选取的文件 BufferedReader buf = new BufferedReader( new FileReader( fileChooser.getSelectedFile())); // 设定文件标题 setTitle(fileChooser.getSelectedFile().toString()); // 清除前一次文件 textArea.setText(""); // 设定状态栏 stateBar.setText("未修改"); // 取得系统相依的换行字符 String lineSeparator = System.getProperty("line.separator"); // 文件并附加至文字编辑区 String text; while((text = buf.readLine()) != null) { textArea.append(text); textArea.append(lineSeparator); } buf.close(); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "开启文件失败", JOptionPane.ERROR_MESSAGE); } } } private void saveFile() { // 从标题栏取得文件名称 File file = new File(getTitle()); // 若指定的文件不存在 if(!file.exists()) { // 执行另存为 saveFileAs(); } else { try { // 开启指定的文件 BufferedWriter buf = new BufferedWriter( new FileWriter(file)); // 将文字编辑区的文字文件 buf.write(textArea.getText()); buf.close(); // 设定状态栏为未修改 stateBar.setText("未修改"); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "文件失败", JOptionPane.ERROR_MESSAGE); } } } private void saveFileAs() { // 显示文件对话框 int option = fileChooser.showSaveDialog(null); // 如果确认选取文件 if(option == JFileChooser.APPROVE_OPTION) { // 取得选择的文件 File file = fileChooser.getSelectedFile(); // 在标题栏上设定文件名称 setTitle(file.toString()); try { // 建立文件 file.createNewFile(); // 进行文件保存 saveFile(); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "无法建立新文件", JOptionPane.ERROR_MESSAGE); } } } private void closeFile() { // 是否已保存文件 if(isCurrentFileSaved()) { // 释放窗口资源,而后关闭程序 dispose(); } else { int option = JOptionPane.showConfirmDialog( null, "文件已修改,是否保存?", "保存文件?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); switch(option) { case JOptionPane.YES_OPTION: saveFile(); break; case JOptionPane.NO_OPTION: dispose(); } } } private void cut() { textArea.cut(); stateBar.setText("已修改"); popUpMenu.setVisible(false); } private void copy() { textArea.copy(); popUpMenu.setVisible(false); } private void paste() { textArea.paste(); stateBar.setText("已修改"); popUpMenu.setVisible(false); } private void processTextArea() { stateBar.setText("已修改"); } public static void main(String[] args) { new JNotePadUI(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值