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

📄 editortabpage.java

📁 java实现的文本编辑器
💻 JAVA
字号:
package MulitePageEditor;

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.*;

//import 记事本.Notepad.RedoAction;
//import 记事本.Notepad.UndoAction;
//import 记事本.Notepad.UndoHandler;

/*******************************************************************************
 * 多Tab页文本编辑器的Tab类继承自JScrollPane,为主窗口提供Tab页 已支持并简化多页实现难度,哈哈采用了我写的浏览器的技术,不过C#
 * 中有TabPage类,Java中的TabControl使用有点不一样,好像组件都可加入其中 而C#只允许加入TabPage.
 * 
 * java中的滚动支持有点奇怪,可是使用也蛮容易的,就是感觉有点怪
 * 
 * java中的异常处理能有效防止异常处理的滥用,如果你要使用try....catch
 * 块,try内必须要有会抛出异常的代码,否则,会不能通过编译.不过这样也有 限制作用,有时可能自己的代码缺陷,而产生异常,却不能捕获,就变得不方便了
 * 不过可以帮助程序员写出无bug的程序.有好处也有不好的地方吧.
 * 
 * java中的属性支持非常的不雅观,没C#,VB之类的语言那么来得优雅,简单,虽然 编译后还是都会有get,set方法,
 * 
 * java中的事件其实是采用了接口回调的一种方式处理,没有C#委托回调机制那么好
 * 还有java中能处理的事件好像有点少,也不是很直接,不过加上匿名内部类,总算还过 得去.
 * 
 * java的io处理有点过于灵活,使用有点难度,对于处理中文支持有点问题,还没找到
 * 什么改变编码的好的方法,试着用Charset解码还是有问题.不知道怎么解决,期待 解决.
 * 
 * 时间: 2006-9-7 作者: 风中过客 声明: 这是第一次写的java程序,不当之处还请指点
 ******************************************************************************/

public class EditorTabPage extends JScrollPane implements IEditorTabPage,
		IDocumentChanged
{
	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;

	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
	//			.removeDocumentListener(new editordocument_documentAdapter(this)); // 为文档模型添加事件处理
	//	editordocument.removeUndoableEditListener(undoHandler);

		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 String OpenFileName;
	private void OpenRTFHtmlFile()
	{
		OpenRTFThread open = new OpenRTFThread();
		open.start();
	}

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

	private void OpenJRFFile()
	{
		
	}
	
	class OpenJRFThread extends Thread
	{
		public void run()
		{
			
		}
	}
	
	class SaveJRFThread extends Thread
	{
		public void run()
		{
			
		}
	}
	/**
	 * 实现复制功能
	 */
	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 Find()
	{
		//TODO: 查找
	}

	public void InsertDataTime()
	{
		//TODO: 获取当前日期和时间
		Calendar cl=Calendar.getInstance();
		Date da=cl.getTime();
	//	DateFormat df=DateFormat.getDateInstance();
	//	System.out.println(/*df.format(da)*/da.toLocaleString()); //该方法以被废弃
		editor.replaceSelection(da.toLocaleString());
	}

	public void LoadFile(String filename)
	{
		//该方法已被废弃
	}

	public void PageSetup()
	{
		//TODO:
	}

	public void Paste()
	{		
		editor.paste();
	}

	public void Print()
	{
		//TODO:
	}

	public void PrintPreview()
	{
        //TODO:
	}

	public void Redo()
	{
		//return redoAction;
		redoAction.actionPerformed(null);
	}

	private String savefilename;

	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()
	{
		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("Unable to undo: " + 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("Unable to redo: " + 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 + -