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

📄 editortabpage.java

📁 多页文本编辑器
💻 JAVA
字号:
/*
 * EditorTabPage.java
 *
 * Created on 2007年10月22日, 上午11:33
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package multipageeditor;

/**
 *
 * @author linda
 */

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

public class EditorTabPage extends JScrollPane {
	private String _filename = null;
	private JEditorPane editor = null;	
	private boolean ischange=false;//是否已经改变了文档内容
	private Font foreFont=new Font("宋体",Font.PLAIN,14);
	private Color fontcolor=Color.BLACK;
	private Color backcolor=Color.WHITE;
	private Document editordocument=null;
	private String OpenFileName;
	private String savefilename;

	public EditorTabPage() {//无参数构造方法
		super(); // 调用基类构造方法
		editor = new JEditorPane();
		editor.setFont(foreFont);
		editordocument = editor.getDocument(); // 设置文档模型
		editordocument.addDocumentListener(new 
                        editordocument_documentAdapter(this)); // 为文档模型添加事件处理
		editordocument.addUndoableEditListener(undoHandler);
		this.getViewport().add(editor); // 为editor提供滚动支持
		resetUndoManager();
		ischange=false;
	}

	public EditorTabPage(String filename) {//带参数构造方法
		this(); // 调用无参数构造方法
		_filename = filename;
		if (_filename.endsWith(".rtf") || _filename.endsWith(".html")
				|| _filename.endsWith("htm")) {
			OpenFileName="file:\\" + _filename;
			OpenRTFHtmlFile();
		} 
                else {
			OpenTXTAndElseFile();
		}
		editordocument = editor.getDocument();
		editordocument.addDocumentListener(new 
                        editordocument_documentAdapter(this)); // 为文档模型添加事件处理
		editordocument.addUndoableEditListener(undoHandler);
		resetUndoManager();
		ischange=false;
	}

	private void OpenTXTAndElseFile() {//打开文本文档
		OpenTXTThread open = new OpenTXTThread();
		open.start();
	}

	class OpenTXTThread extends Thread {//打开文本文档的线程运行方法
		public void run() {
			FileReader file = null;
			BufferedReader br = null;
			try {
				file = new FileReader(_filename);
				br = new BufferedReader(file);
				String line;
				StringBuffer buffer = new StringBuffer();
				while ((line = br.readLine()) != null) {
					buffer.append(line + "\n");
				}
				file.close();
				br.close();
				editor.setText(buffer.toString());
			} 
                        catch (IOException ex) {
				JOptionPane.showMessageDialog(null, _filename
						+ " 文件打开时发生了IO异常,或许该文件不存在!\n" + ex.toString());
			}
			ischange=false;
		}
	}

	private void OpenRTFHtmlFile() {//打开RTF文档
		OpenRTFThread open = new OpenRTFThread();
		open.start();
	}

	class OpenRTFThread extends Thread {//打开RTF文档的线程运行方法
		public void run() {
			try {
				editor.setPage(OpenFileName);
			} 
                        catch (IOException ex) {
				JOptionPane.showMessageDialog(null, _filename
						+ " 文件打开时发生了IO异常,或许该文件不存在!\n" + ex.toString());
			}
			ischange=false;
		}
	}

	// 实现复制功能
	public void Copy() {
		editor.copy();
	}
	// 实现剪切功能
	public void Cut() {		
		editor.cut();
	}
	// 实现删除功能
	public void Delete() {
		editor.replaceSelection("");
	}
	// 实现全部清空功能
	public void DeleteAll() {		
		editor.setText("");
	}
	// 实现隐藏功能
	public void Dispose() {
		this.remove(editor);
	}
	//插入日期和时间
	public void InsertDataTime() {
		//获取当前日期和时间
                Date d = new Date();
                String s; 
                s = DateFormat.getDateInstance(DateFormat.FULL).format(d)+
                        DateFormat.getTimeInstance(DateFormat.FULL).format(d); 
		editor.replaceSelection(s);
	}
	// 实现粘贴功能
        public void Paste() {		
		editor.paste();
	}
	// 实现重做功能
	public void Redo() {
		redoAction.actionPerformed(null);
	}
	// 实现另存为功能
	public void SaveAsDocument() {
		JFileChooser save=new JFileChooser();
		save.setMultiSelectionEnabled(false);
		save.setDialogTitle("保存文件");
		int result=save.showSaveDialog(this);
		if(result==JFileChooser.APPROVE_OPTION) { //按下确定按钮
			String str=save.getSelectedFile().getPath();
			_filename=str;
			SaveDocument();
		}
	}

	class Filter implements FilenameFilter {//文件过滤器
            public boolean accept(File dir, String name) {
              if(name.endsWith(".txt") || name.endsWith(".rtf")) {
            	  return true;
              }
              else {
            	  return false;
              }
            }
	}

	class SaveThread extends Thread {//保存文档的线程运行方法
		public void run() {
			String strdoc = editor.getText();
			try {
				FileWriter file = new FileWriter(savefilename);
				BufferedWriter writer = new BufferedWriter(file);
				writer.write(strdoc);
				writer.flush();
				file.close();
				writer.close();
			} 
                        catch (IOException ex) {
				JOptionPane.showMessageDialog(null, savefilename + " 文件保存失败!",
						"错误", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	public void SaveDocument() {	//保存文档	
		if (_filename == null) {
			SaveAsDocument();
			return;
		}
		savefilename = _filename;
		if(savefilename==null) {
			JOptionPane.showMessageDialog(null, "保存的文件名为空,请重新选择保存的文件名");
			SaveAsDocument();
		}
		SaveThread save = new SaveThread();
		save.start();
	}
	// 实现全选功能
	public void SelectAll() {
		editor.selectAll();
	}
	// 实现撤销功能
	public void Undo() {
		 undoAction.actionPerformed(null);
	}
	// 实现背景色功能
	public Color getBackColor() {
		return backcolor;
	}

	public boolean IsDocChanged() {//判断文档是否进行了修改
		return ischange;
	}
	public Font getDocumentFont() {//获取文档字体
		return foreFont;
	}

	public JEditorPane getEditor() {//获取JEditorPane对象
		return editor;
	}

	public String getFileName() {//获取文件名
		return _filename;
	}

	public Color getFontColor() {//获取字体颜色
		return fontcolor;
	}

	public String getSelectText() {//获取选择的文本
		return editor.getSelectedText();
	}

	public boolean getIsDocumentChanged() {//获取文档改变信息
		return ischange;
	}
	public void setBackColor(Color color) {//设置背景色
		backcolor=color;
		editor.setBackground(backcolor);
	}

	public void setDocumentFont(Font font) {//设置字体
		foreFont=font;
		editor.setFont(foreFont);
	}

	public void setFontColor(Color color) {//设置字体颜色
		fontcolor=color;
		editor.setForeground(fontcolor);
	}

	// 文档被改变
	public void editordocument_changedUpdate(DocumentEvent e) {
		ischange=true;
	}

	//文档插入了文本
	public void editordocument_insertUpdate(DocumentEvent e) {
		ischange=true;
	}

	//文档移除了文本
	public void editordocument_removeUpdate(DocumentEvent e) {
		ischange=true;
	}

	public Document getDocument() {//获取文档
		return editordocument;
	}

	//撤销和重做
	class UndoHandler implements UndoableEditListener {

		/**
		 * Messaged when the Document has created an edit, the edit is added to
		 * <code>undo</code>, an instance of UndoManager.
		 */
		public void undoableEditHappened(UndoableEditEvent e) {
			undo.addEdit(e.getEdit());
			undoAction.update();
			redoAction.update();
		}
	}

	protected UndoManager undo = new UndoManager();
	private UndoAction undoAction = new UndoAction();
	private RedoAction redoAction = new RedoAction();
	protected UndoableEditListener undoHandler = new UndoHandler();

	class UndoAction extends AbstractAction {
		public UndoAction() {
			super("Undo");
			setEnabled(false);
		}

		public void actionPerformed(ActionEvent e) {
			try {
				undo.undo();
			} 
                        catch (CannotUndoException ex) {
				System.out.println("无法撤销: " + ex);
				ex.printStackTrace();
			}
			update();
			redoAction.update();
		}

		protected void update() {
			if (undo.canUndo()) {
				setEnabled(true);
				putValue(Action.NAME, undo.getUndoPresentationName());
			} 
                        else {
				setEnabled(false);
				putValue(Action.NAME, "Undo");
			}
		}
	}

	protected void resetUndoManager() {
		undo.discardAllEdits();
		undoAction.update();
		redoAction.update();
	}

	class RedoAction extends AbstractAction {
		public RedoAction() {
			super("Redo");
			setEnabled(false);
		}

		public void actionPerformed(ActionEvent e) {
			try {
				undo.redo();
			} 
                        catch (CannotRedoException ex) {
				System.out.println("无法重做: " + ex);
				ex.printStackTrace();
			}
			update();
			undoAction.update();
		}

		protected void update() {
			if (undo.canRedo()) {
				setEnabled(true);
				putValue(Action.NAME, undo.getRedoPresentationName());
			} 
                        else {
				setEnabled(false);
				putValue(Action.NAME, "Redo");
			}
		}
	}
}

class editordocument_documentAdapter implements
		javax.swing.event.DocumentListener {// 文档模型事件
	EditorTabPage adaptee;
	editordocument_documentAdapter(EditorTabPage adaptee) {
		this.adaptee = adaptee;
	}

	public void changedUpdate(DocumentEvent e) {
		adaptee.editordocument_changedUpdate(e);
	}

	public void insertUpdate(DocumentEvent e) {
		adaptee.editordocument_insertUpdate(e);
	}

	public void removeUpdate(DocumentEvent e) {
		adaptee.editordocument_removeUpdate(e);
	}
}

⌨️ 快捷键说明

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