使用JAVA swing实现简单的记事本

最近刚学完java swing就做个记事本玩玩,有些功能还没实现,还有很多不足之处

本记事本具有查找、新建、保存、另存为、打开、设置字体、设置字体颜色、设置背景颜色、状态栏等功能。


以下是主函数:

package cslg.yao.main;

import java.awt.EventQueue;

import cslg.yao.Frame.MyFrame;

public class Mainview {
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					MyFrame frame=new MyFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}


以下是实现函数:

package cslg.yao.Frame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
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.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
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.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import cslg.yao.font.MyFont;



public class MyFrame extends JFrame implements ActionListener,DocumentListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 8141051389716751825L;
	//菜单  
	JMenu fileMenu,editMenu,formatMenu,viewMenu,helpMenu;
	//“文件”的菜单项  
	JMenuItem fileMenu_New,fileMenu_Open,fileMenu_Save,fileMenu_SaveAs,fileMenu_PageSetUp,fileMenu_Print,fileMenu_Exit;  
	//“编辑”的菜单项  
	JMenuItem editMenu_Undo,editMenu_Cut,editMenu_Copy,editMenu_Paste,editMenu_Delete,editMenu_Find,editMenu_FindNext,editMenu_Replace,editMenu_GoTo,editMenu_SelectAll,editMenu_TimeDate;  
	//“格式”的菜单项  
	JCheckBoxMenuItem formatMenu_LineWrap;  
	JMenuItem formatMenu_Font,formatMenu_BackColor,formatMenu_FrontColor;  
	//“查看”的菜单项  
	JCheckBoxMenuItem viewMenu_Status;  
	//“帮助”的菜单项  
	JMenuItem helpMenu_HelpTopics,helpMenu_AboutNotepad;
	//右键弹出菜单项  
	JPopupMenu popupMenu;  
	JMenuItem popupMenu_Undo,popupMenu_Cut,popupMenu_Copy,popupMenu_Paste,popupMenu_Delete,popupMenu_SelectAll;  
	//“文本”编辑区域  
	JTextArea editArea;  
	//状态栏标签  
	JLabel statusLabel;
	JLabel statusLabel2;
	//滚动条
	JScrollPane scroller;

	//系统剪贴板  
	Toolkit toolkit=Toolkit.getDefaultToolkit();  
	Clipboard clipBoard=toolkit.getSystemClipboard();  
	//创建撤销操作管理器(与撤销操作有关)  
	protected UndoManager undo=new UndoManager();  
	protected UndoableEditListener undoHandler=new UndoHandler();

	boolean isNewFile=true;//是否新文件(未保存过的)
	String oldValue;//存放编辑区原来的内容,用于比较文本是否有改动  
	File currentFile;//当前文件名  
	Font myFont;
	//构造函数
	public MyFrame() {
		initMenu();
		initFrame();
		Timer t = new Timer(true);
		MyTask task=new MyTask();
		t.schedule(task,1000,1000);
		
	}//构造函数结束
	//初始化菜单
	public void initMenu(){
		//设置菜单栏
		JMenuBar menuBar=new JMenuBar();  
		//创建文件菜单及菜单项并注册事件监听  
		fileMenu=new JMenu("文件(F)");  
		fileMenu.setMnemonic('F');//设置快捷键ALT+F  

		fileMenu_New=new JMenuItem("新建(N)");  
		fileMenu_New.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));  
		fileMenu_New.addActionListener(this);  

		fileMenu_Open=new JMenuItem("打开(O)...");  
		fileMenu_Open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));  
		fileMenu_Open.addActionListener(this);  

		fileMenu_Save=new JMenuItem("保存(S)");  
		fileMenu_Save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));  
		fileMenu_Save.addActionListener(this);  

		fileMenu_SaveAs=new JMenuItem("另存为(A)...");  
		fileMenu_SaveAs.addActionListener(this);  

		fileMenu_PageSetUp=new JMenuItem("页面设置(U)...");  
		fileMenu_PageSetUp.addActionListener(this);  

		fileMenu_Print=new JMenuItem("打印(P)...");  
		fileMenu_Print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK));   
		fileMenu_Print.addActionListener(this);  

		fileMenu_Exit=new JMenuItem("退出(X)");  
		fileMenu_Exit.addActionListener(this);

		//创建编辑菜单及菜单项并注册事件监听  
		editMenu=new JMenu("编辑(E)");  
		editMenu.setMnemonic('E');//设置快捷键ALT+E  
		//当选择编辑菜单时,设置剪切、复制、粘贴、删除等功能的可用性  
		editMenu.addMenuListener(new MenuListener()  
		{   
			public void menuCanceled(MenuEvent e)//取消菜单时调用  
			{   
				checkMenuItemEnabled();//设置剪切、复制、粘贴、删除等功能的可用性  
			}  
			public void menuDeselected(MenuEvent e)//取消选择某个菜单时调用  
			{   
				checkMenuItemEnabled();//设置剪切、复制、粘贴、删除等功能的可用性  
			}  
			public void menuSelected(MenuEvent e)//选择某个菜单时调用  
			{   
				checkMenuItemEnabled();//设置剪切、复制、粘贴、删除等功能的可用性  
			}  
		});  

		editMenu_Undo=new JMenuItem("撤销(U)");  
		editMenu_Undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,InputEvent.CTRL_MASK));  
		editMenu_Undo.addActionListener(this);  
		editMenu_Undo.setEnabled(false);  

		editMenu_Cut=new JMenuItem("剪切(T)");  
		editMenu_Cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));  
		editMenu_Cut.addActionListener(this);  

		editMenu_Copy=new JMenuItem("复制(C)");  
		editMenu_Copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));  
		editMenu_Copy.addActionListener(this);  

		editMenu_Paste=new JMenuItem("粘贴(P)");  
		editMenu_Paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));  
		editMenu_Paste.addActionListener(this);  

		editMenu_Delete=new JMenuItem("删除(D)");  
		editMenu_Delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));  
		editMenu_Delete.addActionListener(this);  

		editMenu_Find=new JMenuItem("查找(F)...");  
		editMenu_Find.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.CTRL_MASK));  
		editMenu_Find.addActionListener(this);  

		editMenu_FindNext=new JMenuItem("查找下一个(N)");  
		editMenu_FindNext.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));  
		editMenu_FindNext.addActionListener(this);  

		editMenu_Replace = new JMenuItem("替换(R)...",'R');   
		editMenu_Replace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_MASK));   
		editMenu_Replace.addActionListener(this);  

		editMenu_GoTo = new JMenuItem("转到(G)...",'G');   
		editMenu_GoTo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK));   
		editMenu_GoTo.addActionListener(this);  

		editMenu_SelectAll = new JMenuItem("全选",'A');   
		editMenu_SelectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));   
		editMenu_SelectAll.addActionListener(this);  

		editMenu_TimeDate = new JMenuItem("时间/日期(D)",'D');  
		editMenu_TimeDate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));  
		editMenu_TimeDate.addActionListener(this);  

		//创建格式菜单及菜单项并注册事件监听  
		formatMenu=new JMenu("格式(O)");  
		formatMenu.setMnemonic('O');//设置快捷键ALT+O  

		formatMenu_LineWrap=new JCheckBoxMenuItem("自动换行(W)");  
		formatMenu_LineWrap.setMnemonic('W');//设置快捷键ALT+W  
		formatMenu_LineWrap.setState(true);  
		formatMenu_LineWrap.addActionListener(this);  

		formatMenu_Font=new JMenuItem("字体(F)...");  
		formatMenu_Font.addActionListener(this);

		formatMenu_BackColor=new JMenuItem("设置背景颜色");
		formatMenu_BackColor.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B,InputEvent.SHIFT_MASK+InputEvent.ALT_MASK));
		formatMenu_BackColor.addActionListener(this);

		formatMenu_FrontColor=new JMenuItem("设置字体颜色");
		formatMenu_FrontColor.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.SHIFT_MASK+InputEvent.ALT_MASK));
		formatMenu_FrontColor.addActionListener(this);

		//创建查看菜单及菜单项并注册事件监听  
		viewMenu=new JMenu("查看(V)");  
		viewMenu.setMnemonic('V');//设置快捷键ALT+V  

		viewMenu_Status=new JCheckBoxMenuItem("状态栏(S)");  
		viewMenu_Status.setMnemonic('S');//设置快捷键ALT+S  
		viewMenu_Status.setState(true);  
		viewMenu_Status.addActionListener(this);  

		//创建帮助菜单及菜单项并注册事件监听  
		helpMenu = new JMenu("帮助(H)");  
		helpMenu.setMnemonic('H');//设置快捷键ALT+H  

		helpMenu_HelpTopics = new JMenuItem("帮助主题(H)");   
		helpMenu_HelpTopics.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1,0));  
		helpMenu_HelpTopics.addActionListener(this);  

		helpMenu_AboutNotepad = new JMenuItem("关于记事本(A)");   
		helpMenu_AboutNotepad.addActionListener(this);  

		//向菜单条添加"文件"菜单及菜单项  
		menuBar.add(fileMenu);   
		fileMenu.add(fileMenu_New);   
		fileMenu.add(fileMenu_Open);   
		fileMenu.add(fileMenu_Save);   
		fileMenu.add(fileMenu_SaveAs);   
		fileMenu.addSeparator();        //分隔线  
		fileMenu.add(fileMenu_PageSetUp);   
		fileMenu.add(fileMenu_Print);   
		fileMenu.addSeparator();        //分隔线   
		fileMenu.add(fileMenu_Exit);   

		//向菜单条添加"编辑"菜单及菜单项   
		menuBar.add(editMenu);   
		editMenu.add(editMenu_Undo);    
		editMenu.addSeparator();        //分隔线   
		editMenu.add(editMenu_Cut);   
		editMenu.add(editMenu_Copy);   
		editMenu.add(editMenu_Paste);   
		editMenu.add(editMenu_Delete);   
		editMenu.addSeparator();        //分隔线  
		editMenu.add(editMenu_Find);   
		editMenu.add(editMenu_FindNext);   
		editMenu.add(editMenu_Replace);  
		editMenu.add(editMenu_GoTo);   
		editMenu.addSeparator();        //分隔线  
		editMenu.add(editMenu_SelectAll);   
		editMenu.add(editMenu_TimeDate);  

		//向菜单条添加"格式"菜单及菜单项        
		menuBar.add(formatMenu);   
		formatMenu.add(formatMenu_LineWrap);   
		formatMenu.add(formatMenu_Font);
		formatMenu.add(formatMenu_BackColor);
		formatMenu.add(formatMenu_FrontColor);

		//向菜单条添加"查看"菜单及菜单项   
		menuBar.add(viewMenu);   
		viewMenu.add(viewMenu_Status);  

		//向菜单条添加"帮助"菜单及菜单项  
		menuBar.add(helpMenu);  
		helpMenu.add(helpMenu_HelpTopics);  
		helpMenu.addSeparator();  
		helpMenu.add(helpMenu_AboutNotepad);  

		//向窗口添加菜单条                
		this.setJMenuBar(menuBar);  

		//创建文本编辑区并添加滚动条  
		editArea=new JTextArea(20,50);  
		scroller=new JScrollPane(editArea);  
		scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);  
		this.add(scroller,BorderLayout.CENTER);//向窗口添加文本编辑区  
		editArea.setWrapStyleWord(true);//设置单词在一行不足容纳时换行  
		editArea.setLineWrap(true);//设置文本编辑区自动换行默认为true,即会"自动换行"  
		//this.add(editArea,BorderLayout.CENTER);//向窗口添加文本编辑区  
		oldValue=editArea.getText();//获取原文本编辑区的内容  

		//编辑区注册事件监听(与撤销操作有关)  
		editArea.getDocument().addUndoableEditListener(undoHandler);  
		editArea.getDocument().addDocumentListener(this);  

		//创建右键弹出菜单  
		popupMenu=new JPopupMenu();  
		popupMenu_Undo=new JMenuItem("撤销(U)");  
		popupMenu_Cut=new JMenuItem("剪切(T)");  
		popupMenu_Copy=new JMenuItem("复制(C)");  
		popupMenu_Paste=new JMenuItem("粘帖(P)");  
		popupMenu_Delete=new JMenuItem("删除(D)");  
		popupMenu_SelectAll=new JMenuItem("全选(A)");  

		popupMenu_Undo.setEnabled(false);  

		//向右键菜单添加菜单项和分隔符  
		popupMenu.add(popupMenu_Undo);  
		popupMenu.addSeparator();  
		popupMenu.add(popupMenu_Cut);  
		popupMenu.add(popupMenu_Copy);  
		popupMenu.add(popupMenu_Paste);  
		popupMenu.add(popupMenu_Delete);  
		popupMenu.addSeparator();  
		popupMenu.add(popupMenu_SelectAll);  

		//文本编辑区注册右键菜单事件  
		popupMenu_Undo.addActionListener(this);  
		popupMenu_Cut.addActionListener(this);  
		popupMenu_Copy.addActionListener(this);  
		popupMenu_Paste.addActionListener(this);  
		popupMenu_Delete.addActionListener(this);  
		popupMenu_SelectAll.addActionListener(this);

		//文本编辑区注册右键菜单事件  
		editArea.addMouseListener(new MouseAdapter()  
		{   
			public void mousePressed(MouseEvent e)  
			{   
				if(e.isPopupTrigger())//返回此鼠标事件是否为该平台的弹出菜单触发事件  
				{   
					popupMenu.show(e.getComponent(),e.getX(),e.getY());//在组件调用者的坐标空间中的位置 X、Y 显示弹出菜单  
				}  
				checkMenuItemEnabled();//设置剪切,复制,粘帖,删除等功能的可用性  
				editArea.requestFocus();//编辑区获取焦点  
			}  
			public void mouseReleased(MouseEvent e)  
			{   
				if(e.isPopupTrigger())//返回此鼠标事件是否为该平台的弹出菜单触发事件  
				{   
					popupMenu.show(e.getComponent(),e.getX(),e.getY());//在组件调用者的坐标空间中的位置 X、Y 显示弹出菜单  
				}  
				checkMenuItemEnabled();//设置剪切,复制,粘帖,删除等功能的可用性  
				editArea.requestFocus();//编辑区获取焦点  
			}  
		});//文本编辑区注册右键菜单事件结束  

		//创建和添加状态栏  
		JPanel panel1=new JPanel();

		statusLabel=new JLabel("");
		statusLabel2=new JLabel("文件状态");

		panel1.add(statusLabel);
		panel1.add(statusLabel2);

		this.add(panel1,BorderLayout.SOUTH);//向窗口添加状态栏标签  


		//添加窗口监听器  
		addWindowListener(new WindowAdapter()  
		{   
			public void windowClosing(WindowEvent e)  
			{   
				exitWindowChoose();  
			}  
		});  

		checkMenuItemEnabled();  
		editArea.requestFocus();	
	}
	//初始化窗体
	public void initFrame(){
		Properties p = new Properties();
		//设置窗体大小位置
		try {
			if(new File("src/size.properties").exists()){
				p.load(new FileReader("src/size.properties"));
				this.setBounds(Integer.parseInt(p.getProperty("x")), Integer.parseInt(p.getProperty("y")), Integer.parseInt(p.getProperty("width")), Integer.parseInt(p.getProperty("height")));
				myFont = new Font(p.getProperty("FontName"),Integer.parseInt(p.getProperty("FontStyle")),Integer.parseInt(p.getProperty("FontSize")));
				editArea.setFont(myFont);
				editArea.setForeground(new Color(Integer.parseInt(p.getProperty("foreColor"))));
				editArea.setBackground(new Color(Integer.parseInt(p.getProperty("backColor"))));
			}else{
				this.setSize(640,480);
				this.setLocationRelativeTo(null);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		//设置子对话框关闭但主对话框可以继续保留!!!!!!!
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		//设置图标
		Image img=toolkit.getImage("img/logo.jpg");
		this.setIconImage(img);
		//设置标题名称
		this.setTitle("呱?呱!");
	}//初始化窗体结束
	//设置菜单项的可用性:剪切,复制,粘帖,删除功能
	public void checkMenuItemEnabled()  
	{   
		String selectText=editArea.getSelectedText();  
		if(selectText==null)  
		{   
			editMenu_Cut.setEnabled(false);  
			popupMenu_Cut.setEnabled(false);  
			editMenu_Copy.setEnabled(false);  
			popupMenu_Copy.setEnabled(false);  
			editMenu_Delete.setEnabled(false);  
			popupMenu_Delete.setEnabled(false);  
		}  
		else  
		{   
			editMenu_Cut.setEnabled(true);  
			popupMenu_Cut.setEnabled(true);   
			editMenu_Copy.setEnabled(true);  
			popupMenu_Copy.setEnabled(true);  
			editMenu_Delete.setEnabled(true);  
			popupMenu_Delete.setEnabled(true);  
		}  
		//粘帖功能可用性判断  
		Transferable contents=clipBoard.getContents(this);  
		if(contents==null)  
		{   
			editMenu_Paste.setEnabled(false);  
			popupMenu_Paste.setEnabled(false);  
		}  
		else  
		{   
			editMenu_Paste.setEnabled(true);  
			popupMenu_Paste.setEnabled(true);     
		}

	}//方法checkMenuItemEnabled()结束  
	//关闭窗口时发生
	public void exitWindowChoose() {
		editArea.requestFocus();
		String currentvalue =editArea.getText();//获取当前编辑域的内容
		//如果当选内容与之前内容无变化,直接退出
		if (currentvalue.equals(oldValue)) {
			setMemory();
			System.exit(0);
		}
		//否则弹出对话框
		else {
			int exitChoose=JOptionPane.showConfirmDialog(this,"您的文件尚未保存,是否保存?","退出提示",JOptionPane.YES_NO_CANCEL_OPTION);
			//当选择是按钮
			if (exitChoose==JOptionPane.YES_OPTION) {
				//判断是否是新文件
				if (isNewFile) {
					savenew();
				}
				//不是新文件
				else {
					savenotnew();
				}
				setMemory();
				System.exit(0);
			}
			else if (exitChoose==JOptionPane.NO_OPTION) {
				setMemory();
				System.exit(0);
			}
			else if (exitChoose==JOptionPane.CANCEL_OPTION) {
				statusLabel2.setText("您没有保存文件!");
				return;
			}
			else {
				return;
			}
		}
	}//结束
	//实现监听器各个功能
	@Override
	public void actionPerformed(ActionEvent e) {
		//新建菜单功能实现
		if (e.getSource()==fileMenu_New) {
			String currentvalue=editArea.getText();
			boolean isTextchange=(currentvalue.equals(oldValue))?true:false;
			//文本内容是否变动
			if (!isTextchange) {
				int saveChoose=JOptionPane.showConfirmDialog(this,"您的文件尚未保存,是否保存?","提示",JOptionPane.YES_NO_CANCEL_OPTION);  
				if(saveChoose==JOptionPane.YES_OPTION)  
				{
					saveother();
				}  
				//当选择否按钮是
				else if(saveChoose==JOptionPane.NO_OPTION)  
				{   
					filenew();
				}
				//当选择取消按钮时
				else if(saveChoose==JOptionPane.CANCEL_OPTION)  
				{   
					statusLabel2.setText("您没有选择新建文件");
					return;  
				} 
			}
			else  
			{   
				filenew();  
			}
		}//新建结束

		//向菜单实现打开功能
		else if (e.getSource()==fileMenu_Open) {
			//			editArea.requestFocus();
			String currentValue=editArea.getText();
			boolean isTextchange=(currentValue.equals(oldValue))?true:false;
			//判断文件是否变动
			if (!isTextchange) {
				int saveChoose=JOptionPane.showConfirmDialog(this,"您的文件尚未保存,是否保存?","提示",JOptionPane.YES_NO_CANCEL_OPTION);
				//当选择是按钮
				if (saveChoose==JOptionPane.YES_OPTION) 
				{
					saveother();
				}
				//当选择否按钮
				else if(saveChoose==JOptionPane.NO_OPTION)  
				{
					fileopen();
				}  
				else  
				{   
					return;  
				}  
			}
			//文件内容无变动执行
			else  
			{
				fileopen();
			}  
		}//打开结束

		//保存
		else if (e.getSource()==fileMenu_Save) {
			//			editArea.requestFocus();
			//是否是新文件
			if(isNewFile)  
			{
				savenew();
			}
			//不是新文件执行
			else  
			{
				savenotnew();
			}  
		}//保存结束

		//另存为
		else if (e.getSource()==fileMenu_SaveAs) {
			saveother();
		}//另存为结束
		//页面设置功能
		else if (e.getSource()==fileMenu_PageSetUp) {
			JOptionPane.showMessageDialog(this,"此功能尚未实现!","提示",JOptionPane.WARNING_MESSAGE);
		}
		//打印功能
		else if (e.getSource()==fileMenu_Print) {
			JOptionPane.showMessageDialog(this,"此功能尚未实现!","提示",JOptionPane.WARNING_MESSAGE);
		}

		//退出功能
		else if (e.getSource()==fileMenu_Exit) {
			exitWindowChoose();
		}//退出结束

		//编辑的撤销功能
		else if(e.getSource()==editMenu_Undo || e.getSource()==popupMenu_Undo)  
		{   

			if(undo.canUndo())  
			{   
				try  
				{   
					undo.undo();  
				}  
				catch (CannotUndoException ex)  
				{   
					System.out.println("Unable to undo:" + ex);  
				}  
			}  
			if(!undo.canUndo())  
			{   
				editMenu_Undo.setEnabled(false);
				popupMenu_Undo.setEnabled(false);
			}  
		}//撤销结束
		//剪切功能
		else if (e.getSource()==editMenu_Cut || e.getSource()==popupMenu_Cut) {
			//			editArea.requestFocus();
			String text =editArea.getSelectedText();
			StringSelection selection=new StringSelection(text);//构建String数据类型
			clipBoard.setContents(selection, null);//添加文本到系统剪切板 
			editArea.replaceRange("",editArea.getSelectionStart(),editArea.getSelectionEnd());
			checkMenuItemEnabled();
		}//功能结束

		//复制功能
		else if (e.getSource()==editMenu_Copy || e.getSource()==popupMenu_Copy) {
			//			editArea.requestFocus();  
			String text=editArea.getSelectedText();  
			StringSelection selection=new StringSelection(text);//构建String数据类型  
			clipBoard.setContents(selection,null);//添加文本到系统剪切板
			checkMenuItemEnabled();
		}//功能结束
		//粘贴功能
		else if (e.getSource()==editMenu_Paste || e.getSource()==popupMenu_Paste) {
			//			editArea.requestFocus();  
			Transferable contents=clipBoard.getContents(this);  
			if(contents==null)
				return;  
			String text="";  
			try  
			{   
				text=(String)contents.getTransferData(DataFlavor.stringFlavor);  //表示 Java Unicode String 类
			}  
			catch (Exception exception)  
			{
				exception.printStackTrace();
			}  
			editArea.replaceRange(text,editArea.getSelectionStart(),editArea.getSelectionEnd());  
			checkMenuItemEnabled();
		}//功能结束

		//删除功能
		else if (e.getSource()==editMenu_Delete || e.getSource()==popupMenu_Delete) {
			//			editArea.requestFocus();
			editArea.replaceRange("",editArea.getSelectionStart(),editArea.getSelectionEnd());
			checkMenuItemEnabled();
		}//功能结束
		//查找功能
		else if (e.getSource()==editMenu_Find) {
			find();
		}//功能结束功能
		//查找下一个
		else if (e.getSource()==editMenu_FindNext) {
			find();
		}//功能结束
		//替换功能
		else if (e.getSource()==editMenu_Replace) {
			JOptionPane.showMessageDialog(this,"此功能尚未实现!","提示",JOptionPane.WARNING_MESSAGE);
		}//功能结束
		//转到功能
		else if (e.getSource()==editMenu_GoTo) {
			JOptionPane.showMessageDialog(this,"此功能尚未实现!","提示",JOptionPane.WARNING_MESSAGE);
		}//功能结束
		//全选功能
		else if (e.getSource()==editMenu_SelectAll || e.getSource()==popupMenu_SelectAll) {
			editArea.selectAll();
		}//功能结束
		//时间日期功能
		else if (e.getSource()==editMenu_TimeDate) {
			Calendar now=Calendar.getInstance();
			Date date =now.getTime();
			editArea.insert(date.toString(),editArea.getCaretPosition());
		}//功能结束
		//自动换行功能(默认设为开启)
		else if (e.getSource()==formatMenu_LineWrap) {
			if(formatMenu_LineWrap.getState())  
				editArea.setLineWrap(true);  
			else   
				editArea.setLineWrap(false);  

		}//功能结束
		//字体设置功能
		else if (e.getSource()==formatMenu_Font) {
			MyFont font=new MyFont(editArea.getFont());
			int returnvalue=font.showFontDialog(this);
			if (returnvalue==font.APPROVE_OPTION) {
				Font f=font.getSelectFont();
				editArea.setFont(f);
			}
			else {
				statusLabel2.setText("未选择新字体!");
				return;
			}
		}//功能结束
		//选择背景颜色功能
		else if (e.getSource()==formatMenu_BackColor) {
			Color c=JColorChooser.showDialog(this,"颜色选择",Color.BLACK);
			editArea.setBackground(c);

		}//功能结束

		else if (e.getSource()==formatMenu_FrontColor) {
			Color c=JColorChooser.showDialog(this,"颜色选择",Color.BLACK);
			editArea.setForeground(c);
		}





		//状态栏功能(默认可见)
		else if (e.getSource()==viewMenu_Status) {
			if(viewMenu_Status.getState()){
				statusLabel.setVisible(true);
				statusLabel2.setVisible(true);
			}  
			else{
				statusLabel.setVisible(false);
				statusLabel2.setVisible(false);
			}   
		}//功能结束
		//帮助主题
		else if (e.getSource()==helpMenu_HelpTopics) {
			JOptionPane.showMessageDialog(this,"此功能尚未实现!","提示",JOptionPane.WARNING_MESSAGE);
		}

		else if (e.getSource()==helpMenu_AboutNotepad) {
			JOptionPane.showMessageDialog(this, "**********************\n"
					+ "*   编写者姚志文    *\n"
					+ "*   2017/8/14            *\n"
					+ "**********************", "呱?呱!", JOptionPane.QUESTION_MESSAGE);
		}

	}
	//记住自己的配置
	public void setMemory(){
		Properties size = new Properties();
		size.setProperty("x", this.getBounds().x+"");
		size.setProperty("y", this.getBounds().y+"");
		size.setProperty("width", this.getBounds().width+"");
		size.setProperty("height", this.getBounds().height+"");
		size.setProperty("FontName", this.editArea.getFont().getFamily());
		size.setProperty("FontStyle", this.editArea.getFont().getStyle()+"");
		size.setProperty("FontSize", this.editArea.getFont().getSize()+"");
		size.setProperty("foreColor", this.editArea.getForeground().getRGB()+"");
		size.setProperty("backColor", this.editArea.getBackground().getRGB()+"");

		FileWriter fr;
		try {
			fr = new FileWriter("src/size.properties");
			size.store(fr, "Size Info");
			fr.close();
		} catch (IOException e2) {
			e2.printStackTrace();
		}
	}
	//新文件时保存
	public void savenew(){

		JFileChooser fileChooser=new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setApproveButtonText("确定");
		fileChooser.setDialogTitle("另存为");

		int result=fileChooser.showSaveDialog(this);
		//如果选择取消向状态栏添加提示
		if (result==JFileChooser.CANCEL_OPTION) {
			statusLabel2.setText("您没有保存文件!");
			return;
		}

		File saveFileName=fileChooser.getSelectedFile();
		if (saveFileName==null||saveFileName.getName().equals("")) {
			JOptionPane.showMessageDialog(this,"不合法的文件名","不合法的文件名",JOptionPane.ERROR_MESSAGE);
		}
		//合法文件名
		else {
			//保存文件
			try {
				OutputStream os=new FileOutputStream(saveFileName);

				OutputStreamWriter osw=new OutputStreamWriter(os);
				//FileWriter fw=new FileWriter(saveFileName);
				//BufferedWriter bfw=new BufferedWriter(fw);
				PrintWriter pw = new PrintWriter(osw);
				pw.write(editArea.getText());
				pw.flush();
				pw.close();

				isNewFile=false;
				currentFile=saveFileName;

				this.setTitle(saveFileName.getName()+"- 呱?呱!");
				statusLabel2.setText("当前文件为:"+saveFileName.getAbsoluteFile());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
	//不是新文件时保存
	public void savenotnew(){
		try {
			OutputStream os=new FileOutputStream(currentFile);
			OutputStreamWriter osw=new OutputStreamWriter(os);
			//FileWriter fw=new FileWriter(currentFile);
			//BufferedWriter bfw=new BufferedWriter(fw);
			PrintWriter pw = new PrintWriter(osw);
			pw.write(editArea.getText());
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//另存为
	public void saveother(){
		JFileChooser fileChooser=new JFileChooser();  
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  
		fileChooser.setDialogTitle("另存为");  
		int result=fileChooser.showSaveDialog(this); 
		//如果选择取消向状态栏添加提示
		if(result==JFileChooser.CANCEL_OPTION)  
		{   
			statusLabel2.setText("您没有选择任何文件");  
			return;  
		}  
		File saveFileName=fileChooser.getSelectedFile();  
		if(saveFileName==null || saveFileName.getName().equals(""))  
		{   
			JOptionPane.showMessageDialog(this,"不合法的文件名","不合法的文件名",JOptionPane.ERROR_MESSAGE);  
		}
		//合法文件名
		else   
		{   
			//保存文件
			try  
			{   
				OutputStream os=new FileOutputStream(saveFileName);
				//FileWriter fw=new FileWriter(saveFileName);  
				//BufferedWriter bfw=new BufferedWriter(fw);
				OutputStreamWriter osw=new OutputStreamWriter(os);
				PrintWriter pw=new PrintWriter(osw);
				pw.write(editArea.getText());  
				pw.flush();
				pw.close();  
				isNewFile=false;  
				currentFile=saveFileName;  
				oldValue=editArea.getText();  
				this.setTitle(saveFileName.getName()+" - 呱?呱!");  
				statusLabel2.setText("当前打开文件:"+saveFileName.getAbsoluteFile());  
			}  
			catch (IOException ioException)  
			{
				ioException.printStackTrace();
			}  
		}  

	}
	//新建文件操作
	public void filenew(){
		editArea.replaceRange("",0,editArea.getText().length());  
		statusLabel2.setText(" 新建文件");  
		this.setTitle("无标题 - 呱?呱!");  
		isNewFile=true;  
		undo.discardAllEdits(); //撤消所有的"撤消"操作  
		editMenu_Undo.setEnabled(false);  
		oldValue=editArea.getText();
	}
	//打开文件操作
	public void fileopen(){

		JFileChooser fileChooser=new JFileChooser();  
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  
		fileChooser.setDialogTitle("打开文件");  
		int result=fileChooser.showOpenDialog(this);
		//如果选择取消向状态栏添加提示
		if(result==JFileChooser.CANCEL_OPTION)  
		{   
			statusLabel2.setText("您没有选择任何文件");  
			return;  
		}  
		File fileName=fileChooser.getSelectedFile();  
		if(fileName==null || fileName.getName().equals(""))  
		{   
			JOptionPane.showMessageDialog(this,"不合法的文件名","不合法的文件名",JOptionPane.ERROR_MESSAGE);  
		}
		//合法文件名
		else  
		{   
			//读取文件
			try  
			{ 
				FileInputStream fis=new FileInputStream(fileName);
				byte[] content=new byte[fis.available()];
				fis.read(content);
				editArea.setText(new String(content));
				editArea.setCaretPosition(0);
				fis.close();

				//				FileChannel fcin = new RandomAccessFile(fileName, "r").getChannel(); 
				//				ByteBuffer rBuffer = ByteBuffer.allocate(1024*1024*7);
				//
				//				try{ 
				//					byte[] bs = new byte[1024*1024*7]; 
				//
				//					while(fcin.read(rBuffer) != -1){ 
				//						int rSize = rBuffer.position(); 
				//						rBuffer.rewind(); 
				//						rBuffer.get(bs); 
				//						rBuffer.clear(); 
				//						String tempString = new String(bs, 0, rSize); 
										System.out.println(tempString);
				//						editArea.setText(tempString);
				//					} 
				//				} catch (IOException e) { 
				//					// TODO Auto-generated catch block 
				//					e.printStackTrace(); 
				//				} 



				this.setTitle(fileName.getName()+" - 呱?呱!");
				statusLabel2.setText(" 当前打开文件:"+fileName.getAbsoluteFile());  
				//fr.close();  
				isNewFile=false;  
				currentFile=fileName;  
				oldValue=editArea.getText();  
			}  
			catch (Exception ioException)  
			{
				ioException.printStackTrace();
			}  
		}  

	}
	//查找方法  
	public void find()  
	{   
		final JDialog findDialog=new JDialog(this,"查找",false);//false时允许其他窗口同时处于激活状态(即无模式)  
		Container con=findDialog.getContentPane();//返回此对话框的contentPane对象      
		con.setLayout(new FlowLayout(FlowLayout.LEFT));  
		JLabel findContentLabel=new JLabel("查找内容(N):");  
		final JTextField findText=new JTextField(15);  
		JButton findNextButton=new JButton("查找下一个(F):");  
		final JCheckBox matchCheckBox=new JCheckBox("区分大小写(C)");  
		ButtonGroup bGroup=new ButtonGroup();  
		final JRadioButton upButton=new JRadioButton("向上(U)");  
		final JRadioButton downButton=new JRadioButton("向下(U)");  
		downButton.setSelected(true);  
		bGroup.add(upButton);  
		bGroup.add(downButton);  
		/*ButtonGroup此类用于为一组按钮创建一个多斥(multiple-exclusion)作用域。 
	        使用相同的 ButtonGroup 对象创建一组按钮意味着“开启”其中一个按钮时,将关闭组中的其他所有按钮。*/  
		/*JRadioButton此类实现一个单选按钮,此按钮项可被选择或取消选择,并可为用户显示其状态。 
	        与 ButtonGroup 对象配合使用可创建一组按钮,一次只能选择其中的一个按钮。 
	        (创建一个 ButtonGroup 对象并用其 add 方法将 JRadioButton 对象包含在此组中。)*/  
		JButton cancel=new JButton("取消");  
		//取消按钮事件处理  
		cancel.addActionListener(new ActionListener()  
		{   
			public void actionPerformed(ActionEvent e)  
			{   
				findDialog.dispose();  
			}  
		});  
		//"查找下一个"按钮监听  
		findNextButton.addActionListener(new ActionListener()  
		{   
			public void actionPerformed(ActionEvent e)  
			{   //"区分大小写(C)"的JCheckBox是否被选中  
				int k=0,m=0;  
				final String str1,str2,str3,str4,strA,strB;  
				str1=editArea.getText();  
				str2=findText.getText();  
				str3=str1.toUpperCase();  
				str4=str2.toUpperCase();  
				if(matchCheckBox.isSelected())//区分大小写  
				{   
					strA=str1;  
					strB=str2;  
				}  
				else//不区分大小写,此时把所选内容全部化成大写(或小写),以便于查找   
				{   
					strA=str3;  
					strB=str4;  
				}  
				if(upButton.isSelected())  
				{   //k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1);  
					if(editArea.getSelectedText()==null)  
						k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1);  
					else  
						k=strA.lastIndexOf(strB, editArea.getCaretPosition()-findText.getText().length()-1);      
					if(k>-1)  
					{   //String strData=strA.subString(k,strB.getText().length()+1);  
						editArea.setCaretPosition(k);  
						editArea.select(k,k+strB.length());  
					}  
					else  
					{   
						JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE);  
					}  
				}  
				else if(downButton.isSelected())  
				{   
					if(editArea.getSelectedText()==null)  
						k=strA.indexOf(strB,editArea.getCaretPosition()+1);  
					else  
						k=strA.indexOf(strB, editArea.getCaretPosition()-findText.getText().length()+1);      
					if(k>-1)  
					{   //String strData=strA.subString(k,strB.getText().length()+1);  
						editArea.setCaretPosition(k);  
						editArea.select(k,k+strB.length());  
					}  
					else  
					{   
						JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE);  
					}  
				}  
			}  
		});//"查找下一个"按钮监听结束  
		//创建"查找"对话框的界面  
		JPanel panel1=new JPanel();  
		JPanel panel2=new JPanel();  
		JPanel panel3=new JPanel();  
		JPanel directionPanel=new JPanel();  
		directionPanel.setBorder(BorderFactory.createTitledBorder("方向"));  
		//设置directionPanel组件的边框;  
		//BorderFactory.createTitledBorder(String title)创建一个新标题边框,使用默认边框(浮雕化)、默认文本位置(位于顶线上)、默认调整 (leading) 以及由当前外观确定的默认字体和文本颜色,并指定了标题文本。  
		directionPanel.add(upButton);  
		directionPanel.add(downButton);  
		panel1.setLayout(new GridLayout(2,1));  
		panel1.add(findNextButton);  
		panel1.add(cancel);  
		panel2.add(findContentLabel);  
		panel2.add(findText);  
		panel2.add(panel1);  
		panel3.add(matchCheckBox);  
		panel3.add(directionPanel);  
		con.add(panel2);  
		con.add(panel3);  
		findDialog.setSize(410,180);  
		findDialog.setResizable(false);//不可调整大小  
		findDialog.setLocation(230,280);  
		findDialog.setVisible(true);  
	}//查找方法结束  
	//内部类实现显示时间
	class MyTask extends TimerTask {
		@Override
		public void run() {
			statusLabel.setText(new Date().toString());
			System.gc();
		}
	} 
	//实现接口UndoableEditListener的类UndoHandler(与撤销操作有关)  
	class UndoHandler implements UndoableEditListener  
	{   
		public void undoableEditHappened(UndoableEditEvent uee)  
		{   
			undo.addEdit(uee.getEdit());  
		}  
	}
	//当文本发生改变
	@Override
	public void changedUpdate(DocumentEvent e) {
		editMenu_Undo.setEnabled(true);
		popupMenu_Undo.setEnabled(true);
	}
	//当文本发生插入
	@Override
	public void insertUpdate(DocumentEvent e) {
		editMenu_Undo.setEnabled(true);
		popupMenu_Undo.setEnabled(true);
	}
	//当文本发生删除
	@Override
	public void removeUpdate(DocumentEvent e) {
		editMenu_Undo.setEnabled(true);
		popupMenu_Undo.setEnabled(true);
	}
}


以下是字体实现函数(引用网上的实现类)

package cslg.yao.font;

import java.awt.BorderLayout;  
import java.awt.Color;  
import java.awt.Dimension;  
import java.awt.Font;  
import java.awt.GraphicsEnvironment;  
import java.awt.event.ActionEvent;  
import java.awt.event.ActionListener;  
import java.awt.event.FocusEvent;  
import java.awt.event.FocusListener;  
import javax.swing.BorderFactory;  
import javax.swing.Box;  
import javax.swing.ButtonGroup;  
import javax.swing.JButton;  
import javax.swing.JDialog;  
import javax.swing.JFrame;  
import javax.swing.JLabel;  
import javax.swing.JList;  
import javax.swing.JOptionPane;  
import javax.swing.JPanel;  
import javax.swing.JRadioButton;  
import javax.swing.JScrollPane;  
import javax.swing.JTextField;  
import javax.swing.event.ListSelectionEvent;  
import javax.swing.event.ListSelectionListener;  
import javax.swing.text.AttributeSet;  
import javax.swing.text.BadLocationException;  
import javax.swing.text.Document;  
import javax.swing.text.PlainDocument;  
/**  
 * 字体选择器,仿记事本中的字体控件,使用操作方法与文件选择器JFileChooser基本相同。  
 * 
 */  
@SuppressWarnings("serial")  
public class MyFont extends JDialog {  
    /**  
     * 选择取消按钮的返回值  
     */  
    public static final int CANCEL_OPTION = 0;  
    /**  
     * 选择确定按钮的返回值  
     */  
    public static final int APPROVE_OPTION = 1;  
    /**  
     * 中文预览的字符串  
     */  
    private static final String CHINA_STRING = "神马都是浮云!";  
    /**  
     * 英文预览的字符串  
     */  
    private static final String ENGLISH_STRING = "Hello Kitty!";  
    /**  
     * 数字预览的字符串  
     */  
    private static final String NUMBER_STRING = "0123456789";  
    // 预设字体,也是将来要返回的字体  
    private Font font = null;  
    // 字体选择器组件容器  
    private Box box = null;  
    // 字体文本框  
    private JTextField fontText = null;  
    // 样式文本框  
    private JTextField styleText = null;  
    // 文字大小文本框  
    private JTextField sizeText = null;  
    // 预览文本框  
    private JTextField previewText = null;  
    // 中文预览  
    private JRadioButton chinaButton = null;  
    // 英文预览  
    private JRadioButton englishButton = null;  
    // 数字预览  
    private JRadioButton numberButton = null;  
    // 字体选择框  
    private JList fontList = null;  
    // 样式选择器  
    private JList styleList = null;  
    // 文字大小选择器  
    private JList sizeList = null;  
    // 确定按钮  
    private JButton approveButton = null;  
    // 取消按钮  
    private JButton cancelButton = null;  
    // 所有字体  
    private String [] fontArray = null;  
    // 所有样式  
    private String [] styleArray = {"常规", "粗体", "斜体", "粗斜体"};  
    // 所有预设字体大小  
    private String [] sizeArray = {"8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "初号", "小初", "一号", "小一", "二号", "小二", "三号", "小三", "四号", "小四", "五号", "小五", "六号", "小六", "七号", "八号"};  
    // 上面数组中对应的字体大小  
    private int [] sizeIntArray = {8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 42, 36, 26, 24, 22, 18, 16, 15, 14, 12, 10, 9, 8, 7, 6, 5};  
    // 返回的数值,默认取消  
    private int returnValue = CANCEL_OPTION;  
    /**  
     * 体构造一个字体选择器  
     */  
    public MyFont() {  
        this(new Font("宋体", Font.PLAIN, 12));  
    }  
    /**  
     * 使用给定的预设字体构造一个字体选择器  
     * @param font 字体  
     */  
    public MyFont(Font font) {  
        setTitle("字体选择器");  
        this.font = font;  
        // 初始化UI组件  
        init();  
        // 添加监听器  
        addListener();  
        // 按照预设字体显示  
        setup();  
        // 基本设置  
        setModal(true);  
        setResizable(false);  
        // 自适应大小  
        pack();  
    }  
    /**  
     * 初始化组件  
     */  
    private void init(){  
        // 获得系统字体  
        GraphicsEnvironment eq = GraphicsEnvironment.getLocalGraphicsEnvironment();  
        fontArray = eq.getAvailableFontFamilyNames();  
        // 主容器  
        box = Box.createVerticalBox();  
        box.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));  
        fontText = new JTextField();  
        fontText.setEditable(false);  
        fontText.setBackground(Color.WHITE);  
        styleText = new JTextField();  
        styleText.setEditable(false);  
        styleText.setBackground(Color.WHITE);  
        sizeText = new JTextField("12");  
        // 给文字大小文本框使用的Document文档,制定了一些输入字符的规则  
        Document doc = new PlainDocument(){  
            public void insertString(int offs, String str, AttributeSet a)  
                    throws BadLocationException {  
                if (str == null) {  
                    return;  
                }  
                if (getLength() >= 3) {  
                    return;  
                }  
                if (!str.matches("[0-9]+") && !str.equals("初号") && !str.equals("小初") && !str.equals("一号") && !str.equals("小一") && !str.equals("二号") && !str.equals("小二") && !str.equals("三号") && !str.equals("小三") && !str.equals("四号") && !str.equals("小四") && !str.equals("五号") && !str.equals("小五") && !str.equals("六号") && !str.equals("小六") && !str.equals("七号") && !str.equals("八号")) {  
                    return;  
                }  
                super.insertString(offs, str, a);  
                sizeList.setSelectedValue(sizeText.getText(), true);  
            }  
        };  
        sizeText.setDocument(doc);  
        previewText = new JTextField(20);  
        previewText.setHorizontalAlignment(JTextField.CENTER);  
        previewText.setEditable(false);  
        previewText.setBackground(Color.WHITE);  
        chinaButton = new JRadioButton("中文预览", true);  
        englishButton = new JRadioButton("英文预览");  
        numberButton = new JRadioButton("数字预览");  
        ButtonGroup bg = new ButtonGroup();  
        bg.add(chinaButton);  
        bg.add(englishButton);  
        bg.add(numberButton);  
        fontList = new JList(fontArray);  
        styleList = new JList(styleArray);  
        sizeList = new JList(sizeArray);  
        approveButton = new JButton("确定");  
        cancelButton = new JButton("取消");  
        Box box1 = Box.createHorizontalBox();  
        JLabel l1 = new JLabel("字体:");  
        JLabel l2 = new JLabel("字形:");  
        JLabel l3 = new JLabel("大小:");  
        l1.setPreferredSize(new Dimension(165, 14));  
        l1.setMaximumSize(new Dimension(165, 14));  
        l1.setMinimumSize(new Dimension(165, 14));  
        l2.setPreferredSize(new Dimension(95, 14));  
        l2.setMaximumSize(new Dimension(95, 14));  
        l2.setMinimumSize(new Dimension(95, 14));  
        l3.setPreferredSize(new Dimension(80, 14));  
        l3.setMaximumSize(new Dimension(80, 14));  
        l3.setMinimumSize(new Dimension(80, 14));  
        box1.add(l1);  
        box1.add(l2);  
        box1.add(l3);  
        Box box2 = Box.createHorizontalBox();  
        fontText.setPreferredSize(new Dimension(160, 20));  
        fontText.setMaximumSize(new Dimension(160, 20));  
        fontText.setMinimumSize(new Dimension(160, 20));  
        box2.add(fontText);  
        box2.add(Box.createHorizontalStrut(5));  
        styleText.setPreferredSize(new Dimension(90, 20));  
        styleText.setMaximumSize(new Dimension(90, 20));  
        styleText.setMinimumSize(new Dimension(90, 20));  
        box2.add(styleText);  
        box2.add(Box.createHorizontalStrut(5));  
        sizeText.setPreferredSize(new Dimension(80, 20));  
        sizeText.setMaximumSize(new Dimension(80, 20));  
        sizeText.setMinimumSize(new Dimension(80, 20));  
        box2.add(sizeText);  
        Box box3 = Box.createHorizontalBox();  
        JScrollPane sp1 = new JScrollPane(fontList);  
        sp1.setPreferredSize(new Dimension(160, 100));  
        sp1.setMaximumSize(new Dimension(160, 100));  
        sp1.setMaximumSize(new Dimension(160, 100));  
        box3.add(sp1);  
        box3.add(Box.createHorizontalStrut(5));  
        JScrollPane sp2 = new JScrollPane(styleList);  
        sp2.setPreferredSize(new Dimension(90, 100));  
        sp2.setMaximumSize(new Dimension(90, 100));  
        sp2.setMinimumSize(new Dimension(90, 100));  
        box3.add(sp2);  
        box3.add(Box.createHorizontalStrut(5));  
        JScrollPane sp3 = new JScrollPane(sizeList);  
        sp3.setPreferredSize(new Dimension(80, 100));  
        sp3.setMaximumSize(new Dimension(80, 100));  
        sp3.setMinimumSize(new Dimension(80, 100));  
        box3.add(sp3);  
        Box box4 = Box.createHorizontalBox();  
        Box box5 = Box.createVerticalBox();  
        JPanel box6 = new JPanel(new BorderLayout());  
        box5.setBorder(BorderFactory.createTitledBorder("字符集"));  
        box6.setBorder(BorderFactory.createTitledBorder("示例"));  
        box5.add(chinaButton);  
        box5.add(englishButton);  
        box5.add(numberButton);  
        box5.setPreferredSize(new Dimension(90, 95));  
        box5.setMaximumSize(new Dimension(90, 95));  
        box5.setMinimumSize(new Dimension(90, 95));  
        box6.add(previewText);  
        box6.setPreferredSize(new Dimension(250, 95));  
        box6.setMaximumSize(new Dimension(250, 95));  
        box6.setMinimumSize(new Dimension(250, 95));  
        box4.add(box5);  
        box4.add(Box.createHorizontalStrut(4));  
        box4.add(box6);  
        Box box7 = Box.createHorizontalBox();  
        box7.add(Box.createHorizontalGlue());  
        box7.add(approveButton);  
        box7.add(Box.createHorizontalStrut(5));  
        box7.add(cancelButton);  
        box.add(box1);  
        box.add(box2);  
        box.add(box3);  
        box.add(Box.createVerticalStrut(5));  
        box.add(box4);  
        box.add(Box.createVerticalStrut(5));  
        box.add(box7);  
        getContentPane().add(box);  
    }  
    /**  
     * 按照预设字体显示  
     */  
    private void setup() {  
        String fontName = font.getFamily();  
        int fontStyle = font.getStyle();  
        int fontSize = font.getSize();  
        /*  
         * 如果预设的文字大小在选择列表中,则通过选择该列表中的某项进行设值,否则直接将预设文字大小写入文本框  
         */  
        boolean b = false;  
        for (int i = 0; i < sizeArray.length; i++) {  
            if (sizeArray[i].equals(String.valueOf(fontSize))) {  
                b = true;  
                break;  
            }  
        }  
        if(b){  
            // 选择文字大小列表中的某项  
            sizeList.setSelectedValue(String.valueOf(fontSize), true);  
        }else{  
            sizeText.setText(String.valueOf(fontSize));  
        }  
        // 选择字体列表中的某项  
        fontList.setSelectedValue(fontName, true);  
        // 选择样式列表中的某项  
        styleList.setSelectedIndex(fontStyle);  
        // 预览默认显示中文字符  
        chinaButton.doClick();  
        // 显示预览  
        setPreview();  
    }  
    /**  
     * 添加所需的事件监听器  
     */  
    private void addListener() {  
        sizeText.addFocusListener(new FocusListener() {  
            public void focusLost(FocusEvent e) {  
                setPreview();  
            }  
            public void focusGained(FocusEvent e) {  
                sizeText.selectAll();  
            }  
        });  
        // 字体列表发生选择事件的监听器  
        fontList.addListSelectionListener(new ListSelectionListener() {  
            public void valueChanged(ListSelectionEvent e) {  
                if (!e.getValueIsAdjusting()) {  
                    fontText.setText(String.valueOf(fontList.getSelectedValue()));  
                    // 设置预览  
                    setPreview();  
                }  
            }  
        });  
        styleList.addListSelectionListener(new ListSelectionListener() {  
            public void valueChanged(ListSelectionEvent e) {  
                if (!e.getValueIsAdjusting()) {  
                    styleText.setText(String.valueOf(styleList.getSelectedValue()));  
                    // 设置预览  
                    setPreview();  
                }  
            }  
        });  
        sizeList.addListSelectionListener(new ListSelectionListener() {  
            public void valueChanged(ListSelectionEvent e) {  
                if (!e.getValueIsAdjusting()) {  
                    if(!sizeText.isFocusOwner()){  
                        sizeText.setText(String.valueOf(sizeList.getSelectedValue()));  
                    }  
                    // 设置预览  
                    setPreview();  
                }  
            }  
        });  
        // 编码监听器  
        EncodeAction ea = new EncodeAction();  
        chinaButton.addActionListener(ea);  
        englishButton.addActionListener(ea);  
        numberButton.addActionListener(ea);  
        // 确定按钮的事件监听  
        approveButton.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
                // 组合字体  
                font = groupFont();  
                // 设置返回值  
                returnValue = APPROVE_OPTION;  
                // 关闭窗口  
                disposeDialog();  
            }  
        });  
        // 取消按钮事件监听  
        cancelButton.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
                disposeDialog();  
            }  
        });  
    }  
    /**  
     * 显示字体选择器  
     * @param owner 上层所有者  
     * @return 该整形返回值表示用户点击了字体选择器的确定按钮或取消按钮,参考本类常量字段APPROVE_OPTION和CANCEL_OPTION  
     */  
    public final int showFontDialog(JFrame owner) {  
        setLocationRelativeTo(owner);  
        setVisible(true);  
        return returnValue;  
    }  
    /**  
     * 返回选择的字体对象  
     * @return 字体对象  
     */  
    public final Font getSelectFont() {  
        return font;  
    }  
    /**  
     * 关闭窗口  
     */  
    private void disposeDialog() {  
    	MyFont.this.removeAll();  
    	MyFont.this.dispose();  
    }  
      
    /**  
     * 显示错误消息  
     * @param errorMessage 错误消息  
     */  
    private void showErrorDialog(String errorMessage) {  
        JOptionPane.showMessageDialog(this, errorMessage, "错误", JOptionPane.ERROR_MESSAGE);  
    }  
    /**  
     * 设置预览  
     */  
    private void setPreview() {  
        Font f = groupFont();  
        previewText.setFont(f);  
    }  
    /**  
     * 按照选择组合字体  
     * @return 字体  
     */  
    private Font groupFont() {  
        String fontName = fontText.getText();  
        int fontStyle = styleList.getSelectedIndex();  
        String sizeStr = sizeText.getText().trim();  
        // 如果没有输入  
        if(sizeStr.length() == 0) {  
            showErrorDialog("字体(大小)必须是有效“数值!");  
            return null;  
        }  
        int fontSize = 0;  
        // 通过循环对比文字大小输入是否在现有列表内  
        for (int i = 0; i < sizeArray.length; i++) {  
            if(sizeStr.equals(sizeArray[i])){  
                fontSize = sizeIntArray[i];  
                break;  
            }  
        }  
        // 没有在列表内  
        if (fontSize == 0) {  
            try{  
                fontSize = Integer.parseInt(sizeStr);  
                if(fontSize < 1){  
                    showErrorDialog("字体(大小)必须是有效“数值”!");  
                    return null;  
                }  
            }catch (NumberFormatException nfe) {  
                showErrorDialog("字体(大小)必须是有效“数值”!");  
                return null;  
            }  
        }  
        return new Font(fontName, fontStyle, fontSize);  
    }  
      
    /**  
     * 编码选择事件的监听动作  
     *  
     */  
    class EncodeAction implements ActionListener {  
        public void actionPerformed(ActionEvent e) {  
            if (e.getSource().equals(chinaButton)) {  
                previewText.setText(CHINA_STRING);  
            } else if (e.getSource().equals(englishButton)) {  
                previewText.setText(ENGLISH_STRING);  
            } else {  
                previewText.setText(NUMBER_STRING);  
            }  
        }  
    }  
      
}  


  • 6
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值