⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cutandpaste.java

📁 用java实现的记事本功能
💻 JAVA
字号:
/*
 * Created on 2005-6-14
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.eagle.test;

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
import java.io.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

import com.eagle.swing.Console;
import java.awt.datatransfer.*;
import javax.swing.undo.UndoManager;


public class CutAndPaste extends JFrame {
	private static final int NotModify = 0;
	private static final int HavModify = 1;
	private static int flag = NotModify;
	
	private JMenuBar mb = new  JMenuBar();
	private JMenu file = new JMenu("File");
	private JMenu edit = new JMenu("Edit");
	private JMenu help = new JMenu("Help");
	private JMenuItem
	   newF = new JMenuItem("New"),
	   open = new JMenuItem("Open"),
       save = new JMenuItem("Save"),	
       close = new JMenuItem("Close"),
	   redo = new JMenuItem("Redo"),
	   undo = new JMenuItem("Undo"),
	   find = new JMenuItem("Find"),
	   cut = new JMenuItem("Cut"),
       copy = new JMenuItem("Copy"),
       paste = new JMenuItem("Paste"),
	   about = new JMenuItem("About");    
    
	private UndoManager undomanager= new UndoManager();
	private JTextArea text = new JTextArea(20,30);
	private TextF textf = new TextF();
	private UndoF undof = new UndoF();
	private Clipboard clipbd = getToolkit().getSystemClipboard();

    public CutAndPaste(){      

    	this.setTitle("无标题-记事本");
    	newF.addActionListener(new NewF());
     	open.addActionListener(new OpenDialog());
    	save.addActionListener(new SaveDialog());
    	close.addActionListener(new CloseF());    	
    	
    	redo.addActionListener(new RedoL());
    	undo.addActionListener(new UndoL());
    	find.addActionListener(new FindL());
    	cut.addActionListener(new CutL());
      	copy.addActionListener(new CopyL());
      	paste.addActionListener(new PasteL()); 
      	
      	about.addActionListener(new AboutH());
      	
      	text.getDocument().addDocumentListener(textf); 
      	text.getDocument().addUndoableEditListener(undof);
      	
      	
      	file.add(newF);
      	file.add(open);
      	file.add(save);
      	file.add(close);
      	
      	edit.add(undo);
      	edit.add(redo);
      	edit.add(find);
      	edit.add(cut);
      	edit.add(copy);
      	edit.add(paste);
      	
      	help.add(about);
      	
      	mb.add(file);
      	mb.add(edit);
      	mb.add(help);
      	
      	setJMenuBar(mb);
      	getContentPane().add(new JScrollPane(text));
    } 
    
    class NewF implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		
    		undomanager.discardAllEdits();
    		if(flag == NotModify) {
    			text.setText("");    			
    			flag = NotModify;
    		}
    		if(flag == HavModify ){ 
    			int val = isSaveDialog();
    			if(val == 0) {
    				SaveF();
    				text.setText("");
    				flag = NotModify;
    			}
    			if(val == 1) {
    				text.setText("");
    				flag = NotModify;
    			}
    			if(val == 2) ;
    		}
    	}
    }
    
    class UndoF implements UndoableEditListener{
     public void undoableEditHappened( UndoableEditEvent e )  
        { 
            undomanager.addEdit( e.getEdit() ); 
        } 
    }
    

    
    class TextF implements DocumentListener{
     	public void changedUpdate(DocumentEvent e){
    		flag = HavModify;
    	}
    	public void insertUpdate(DocumentEvent e){
    		flag = HavModify;
    	}
    	public void removeUpdate(DocumentEvent e){        	
    		flag = HavModify;
    	}
    }
    
    class OpenDialog implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		if(flag == NotModify) OpenF();
    		else if(flag == HavModify) {
    			int value = isSaveDialog();
    			if(value == 0) {
    				SaveF();
    				OpenF();
    			}
    			else if(value == 1) OpenF();
    		}    		
    	}
    }
    
    class SaveDialog implements ActionListener{
    	public void actionPerformed(ActionEvent e){
        if(flag == NotModify) ;    
    	else if(flag == HavModify) {    	
    		SaveF(); 
    		}    			
    	}
    }
    
   
    	public void OpenF(){    		
    		File filer = new File
			("E:\\eclipse\\myworkspace\\MySwing\\com\\eagle\\test");	 		
    	
    			JFileChooser chooser = new JFileChooser(filer); 
    			int returnVal = chooser.showOpenDialog(new CutAndPaste());   			
    			if(returnVal == JFileChooser.APPROVE_OPTION){
    				 text.setText("");    		 
    		      try{
    		      	  	FileReader fr = new FileReader
    					(new File(chooser.getSelectedFile().getAbsolutePath()));
    		    		super.setTitle(chooser.getSelectedFile().getName() + "-记事本");
    		    		BufferedReader br = new BufferedReader(fr);
    		   			String str = br.readLine();
    		   			   while(str != null){    	        	
    		   	        	  text.append(str + "\n");
    		   	        	  str = br.readLine();
    	    	           }     	      
    	    	       br.close();   			
    		    	 }catch(IOException ee){}
    			} 
    			flag = NotModify;              //not to check
    	}
 
  
    	public void SaveF(){
    		File filer = new File
			("E:\\eclipse\\myworkspace\\MySwing\\com\\eagle\\test");	 		
    	
    			JFileChooser chooser = new JFileChooser(filer);
    			int returnVal = chooser.showSaveDialog(new CutAndPaste());   			
    			if(returnVal == JFileChooser.APPROVE_OPTION){    				
    				String content = text.getText();    
    	    		try{
    	    			FileWriter fw = new FileWriter
    					(new File(chooser.getSelectedFile().getAbsolutePath()));
    	    			
    	    			BufferedWriter bw = new BufferedWriter(fw);
    	    			PrintWriter pw = new PrintWriter(bw);
    	    			pw.write(content);
    	    			pw.close();
    	    		}catch(IOException ee){}   	    		
    	    		flag = NotModify;
    			} 
    		
    	}
 
        public int isSaveDialog(){
        	Object[] options = {
        			"  Yes ",
                    "  No  ",
                    "cancel"};
             int n = JOptionPane.showOptionDialog(null,
                 "你编辑的文件中的文字已经改变,需要保存吗?",
                 "我的记事本",
                 JOptionPane.YES_NO_CANCEL_OPTION,
                 JOptionPane.QUESTION_MESSAGE,
                 null,
                 options,
                 options[2]);
             return n;
        }
       
        
    class CloseF implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		if(flag == NotModify){    	      	
    			System.exit(0);     		
    		}
    		
    		int v = isSaveDialog();
    		if(v == 0) {
    			SaveF();    			
    			System.exit(0);
    		}
    		if(v == 1) {    		
    			System.exit(0);
    		}
    			
    	}
    }
    
       
    
    class CutL implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		String selection = text.getSelectedText();
    		if(selection == null){
    			return ;
    		}
    		StringSelection clipString = 
    			new StringSelection(selection);
    		clipbd.setContents(clipString, clipString);
    		text.replaceRange("",
    				text.getSelectionStart(),
					text.getSelectionEnd());   		
    	}
    }
    
    class CopyL implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		String selection = text.getSelectedText();
    		if(selection == null){
    			return ;
    		}
    		StringSelection clipString = 
    			new StringSelection(selection);
    		clipbd.setContents(clipString, clipString);    		
    	}
    }
    
    class PasteL implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		Transferable clipData =
    			clipbd.getContents(CutAndPaste.this);
    		try{
    			String clipString =
    				(String)clipData.getTransferData(DataFlavor.stringFlavor);
    			text.replaceRange(clipString,
    					text.getSelectionStart(),
						text.getSelectionEnd());  
    		}catch(Exception ex){
    			System.err.println("Not String flavor");   			
    		}
    	}
    }
    
    class AboutH implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		JOptionPane.showMessageDialog(null,
             "         版权所有,翻版不究\n " +
             "浙江工业大学软件学院04级 殷正生           ",
			 "我的记事本",
			 JOptionPane.INFORMATION_MESSAGE);    	

    	}
    }
    
    class RedoL implements ActionListener{
    	public void actionPerformed(ActionEvent e){    	
    		
//    	redo.setEnabled(undomanager.canRedo());               //have to modify
    	   if(undomanager.canRedo()){
           	undomanager.redo();        	
          	}
    	   } 
    }
    
    class UndoL implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		
//    		undo.setEnabled(undomanager.canUndo());         //have to modify
    	   if(undomanager.canUndo()){
           	undomanager.undo();           
          	}
    	   } 
    }
    
    class FindL implements ActionListener {    
    	public void actionPerformed(ActionEvent e) {
    		String obj = text.getText();
    		obj = obj.replaceAll("\r\n"," ");
    		
    		int index = 0;
    		int base = 0;
    		int relative = 0;
    		String s = "";
    		try{
    		do{
    			s = (String)JOptionPane.showInputDialog(
	                    null,
	                    "查找内容:" ,
	                    "查找",
	                    JOptionPane.PLAIN_MESSAGE,
	                    null,
						null,
	                    s); 
//    			System.out.println("\ns:" + s);
    			relative = obj.indexOf(s);
    			if(relative == -1){
    				text.select(0,0);
                  	JOptionPane.showMessageDialog(null,
                  			"已经到文件末尾");
                  	break;
    			}
    			index = base + relative;    			
    			text.select(index, index + s.length());   	//sethighlighted 
//    			System.out.println("index:" + index);
//    			System.out.println("relative:" + relative);
    			obj = obj.substring(relative + s.length());    			
    			base = index + s.length();
//    			System.out.print("\nobj2:" + obj);
    		}while(relative > -1);
    		
    		}catch(StringIndexOutOfBoundsException se){
    			text.select(0,0);
              	JOptionPane.showMessageDialog(null,
              			"已经到文件末尾");
    		}
    		catch(NullPointerException ne){
    			
    		}
    		
    		
    	}
    }
	public static void main(String[] args) {
		int width = Toolkit.getDefaultToolkit().getScreenSize().width;
		int height = Toolkit.getDefaultToolkit().getScreenSize().height;
		Console.run(new CutAndPaste(), 3*width/4, 3*height/4);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -